版权声明:本文为博主原创文章,未经博主允许不得转载。
1.用redis中的List可以实现队列,这样可以用来做消息处理和任务调度的队列
2.代码模拟
代码结构
生产者模拟程序
消费者模拟程序
-
-
-
- package scheduleTest;
-
- import java.util.Random;
-
- import redis.clients.jedis.Jedis;
-
-
-
-
-
-
-
-
-
-
- public class TaskConsumer implements Runnable {
- Jedis jedis = new Jedis("120.55.195.177",6379);
-
- public void run() {
- Random random = new Random();
-
- while(true){
-
-
- String taskid = jedis.rpoplpush("task-queue", "tmp-queue");
-
-
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
-
-
- if(random.nextInt(13) % 7 == 0){
-
- jedis.rpoplpush("tmp-queue", "task-queue");
- System.out.println(taskid + "处理失败,被弹回任务队列");
-
- } else {
-
-
- jedis.rpop("tmp-queue");
- System.out.println(taskid+"处理成功,被清除");
-
- }
- }
-
- }
-
-
-
- }
调度主程序
-
-
-
- package scheduleTest;
-
-
-
-
-
-
-
-
-
- public class TaskShedulerSystem {
- public static void main(String[] args) throws Exception {
-
-
- new Thread(new TaskProducer()).start();
-
- Thread.sleep(15000);
-
-
- new Thread(new TaskConsumer()).start();
-
-
- Thread.sleep(Long.MAX_VALUE);
- }
- }
运行结果
此文章来自于【http:///zuoanyinxiang/article/details/50263945】