实现延迟队列的思路
zset的特性,带有分数的排序,以时间戳作为分数进行排序
- 添加任务 zdd
- 取出任务 zrangbyscore
- 执行任务 zrem
定时任务
public static void main(String[] args) {
Jedis jedis = new Jedis("ip", 6379);
TimerTask task = new TimerTask() {
@Override
public 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实现实现延迟队列
*/
@Test
public 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");
}
<iframe allowfullscreen="true" data-mediaembed="bilibili" frameborder="0" id="YysiJtSb-1716686383697" src="https://player.bilibili.com/player.html?aid=1405052598"></iframe>
软考高级之redis中使用zset实现延迟队列,你答对了么?
标签:zset,软考,redis,System,currentTimeMillis,任务,jedis,delayOrderQueue From: https://blog.csdn.net/qq_37400096/article/details/139207744