实现延迟队列的思路
zset的特性,带有分数的排序,以时间戳作为分数进行排序
- 添加任务 zdd
- 取出任务 zrangbyscore
- 执行任务 zrem
定时任务
public static void main(String[] args) {Jedis jedis = new Jedis("ip", 6379);TimerTask task = new TimerTask() {@Overridepublic void run() {// 这里是定时任务的执行代码Set<String> order = jedis.zrangeByScore("delayOrderQueue", System.currentTimeMillis()-10000, System.currentTimeMillis());//取出任务进行执行for (String orderId : order) {Long order1 = jedis.zrem("delayOrderQueue", orderId);System.out.println("执行任务:" + orderId);}}};Timer timer = new Timer();long delay = 0; // 延迟开始执行时间,单位:毫秒long period = 1000; // 定时任务执行间隔,单位:毫秒timer.scheduleAtFixedRate(task,delay,period);}
添加任务
/*** zset实现实现延迟队列*/@Testpublic void TestZet(){long currentTimeMillis = System.currentTimeMillis();System.out.println(currentTimeMillis);jedis.zadd("delayOrderQueue", currentTimeMillis, "1");jedis.zadd("delayOrderQueue", currentTimeMillis+3000, "2");jedis.zadd("delayOrderQueue", currentTimeMillis+5000, "3");}
软考高级之redis中使用zset实现延迟队列,你答对了么?