91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

redis消息隊列如何延時

小新
191
2020-12-25 17:40:57
欄目: 云計算

redis消息隊列如何延時

redis消息隊列延時的示例:

延時隊列可通過zset來實現,消息的處理時間作為score,最后通過多線程輪詢獲取到期的score任務即可,代碼:

public class DelayQueue {

static class TaskItem {

public String id;

public T msg;

}

private Type taskType = new TypeReference>() {

}.getType();

private Jedis jedis;

private String queueName;

public DelayQueue(Jedis jedis, String queueName) {

this.jedis = jedis;

this.queueName = queueName;

}

public void delay(T msg, long delayTime) {

TaskItem task = new TaskItem<>();

task.id = UUID.randomUUID().toString();

task.msg = msg;

jedis.zadd(queueName, System.currentTimeMillis() + delayTime, JSON.toJSONString(task));

}

public void loop() {

while (!Thread.interrupted()) {

Set set = jedis.zrangeByScore(queueName, 0, System.currentTimeMillis(), 0, 1);

if (set.isEmpty()) {

try {

Thread.sleep(500);

} catch (InterruptedException e) {

break;

}

continue;

}

String s = set.iterator().next();

if (jedis.zrem(queueName, s) > 0) {

TaskItem task = JSON.parseObject(s, taskType);

System.out.println(task.msg);

}

}

}

}

2.測試代碼:

public static void main(String[] args) throws InterruptedException {

Jedis jedis = new Jedis("127.0.0.1", 6379);

DelayQueue delayQueue = new DelayQueue<>(jedis, "delay_queue");

Thread producer = new Thread(() -> {

for (int i = 0; i < 10; i++)

delayQueue.delay("Mr.Wang's Hub" + i, 5000);

});

Thread consumer = new Thread(() -> {

delayQueue.loop();

});

consumer.start();

producer.start();

while (Thread.activeCount() > 1)

Thread.yield();

}

0
连州市| 宜宾县| 西青区| 桂东县| 西峡县| 德清县| 吉木萨尔县| 阜平县| 淮滨县| 凤翔县| 修水县| 会理县| 甘德县| 安徽省| 丹巴县| 巴楚县| 宁城县| 祁门县| 紫阳县| 乌拉特后旗| 三河市| 临漳县| 武邑县| 北安市| 沈阳市| 旌德县| 舒兰市| 绥棱县| 广平县| 黔西| 达州市| 平远县| 望江县| 阿城市| 迭部县| 德江县| 三门县| 潼关县| 二连浩特市| 民和| 毕节市|