springboot 基于 redis redisson的 延迟消息队列
消息接收方
delayQueueService.pushData(delayRequest,
initAfterInterval,
DelayQueueConst.CRAWLER_LIST_QUEUE);
消息发送方(随项目启动)
@Slf4j
@Component
public class JumpQueueMessageReceive implements ApplicationRunner {
@Resource
private DelayQueueService<Request> delayQueueService;
@Async("birdsExecutor")
@Override
public void run(ApplicationArguments args) {
while (true){
Request request = null;
try {
request = delayQueueService.pullData(DelayQueueConst.CRAWLER_LIST_QUEUE);
//do some
} catch (InterruptedException e) {
log.info(e.getMessage(),e);
}
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
log.info(e.getMessage(),e);
}
}
}
}
service
@Service
public class DelayQueueService<T> {
@Resource
private RedissonClient redissonClient;
public void pushData(T data, String queueName){
pushData(data, 0, TimeUnit.MILLISECONDS, queueName);
}
public void pushData(T data,long time, String queueName){
pushData(data, time, TimeUnit.MINUTES, queueName);
}
public void pushData(T data, long time, TimeUnit timeUnit, String queueName){
getDelayQueue(queueName).offerAsync(data, time < 0 ? 0 : time, timeUnit);
}
public T pullData(String queueName) throws InterruptedException {
return getBlockingQueue(queueName).take();
}
private RBlockingQueue<T> getBlockingQueue(String queueName) {
return redissonClient.getBlockingQueue(queueName);
}
private RDelayedQueue<T> getDelayQueue(String queueName) {
return redissonClient.getDelayedQueue(getBlockingQueue(queueName));
}
private RDelayedQueue<T> getDelayQueue(RBlockingQueue<T> blockingQueue) {
return redissonClient.getDelayedQueue(blockingQueue);
}
}
完整代码查看
github开源地址(飞鸟小说):https://github.com/caobinrg/birds-novel
gitee开源地址(飞鸟小说) : https://gitee.com/caobinrg/birds-novel