1.加入依赖
<!-- redisson-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.13.6</version>
</dependency>
2.启动延迟队列
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author yhh
* @Description: 启动延迟队列 (如果是微服务,避免被其他服务消费,应该把此RUNNER和ENUM提取到其他相关delay的上一级)
* @date 2022-04-21 15:11
*/
@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {
@Autowired
private RedissonClient redissonClient ;
@Override
public void run(String... args) {
RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
for (RedisDelayQueueEnum queueEnum : queueEnums) {
RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueEnum.getCode());
//避免消息伪丢失(应用重启未消费),官网推荐
redissonClient.getDelayedQueue(blockingDeque) ;
new Thread(() -> {
while (true) {
try {
Object take = blockingDeque.take();
if(take!=null) {
RedisDelayQueueHandle redisDelayQueueHandle = SpringUtil.getBean(queueEnum.getBeanId());
redisDelayQueueHandle.execute(take);
}
} catch (InterruptedException e) {
log.error("(Redis延迟队列异常中断) {}", e.getMessage());
}
}
}).start();
}
log.info("Redis延迟队列启动成功");
}
}
3.延迟队列枚举
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* @author yhh
* @Description:
* @date 2022-04-21 15:20
*/
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum RedisDelayQueueEnum {
ORDER_TIMEOUT("ORDER_TIMEOUT","订单到点失效","orderTimeout"),
USER_COUPON_TIMEOUT_REMINDER("USER_COUPON_TIMEOUT_REMINDER","用户优惠卷过期提醒","userCouponTimeoutReminder"),
WX_MSG_SEND("WX_MSG_SEND","消息发送","wxMsgSendTask")
;
/**
* 延迟队列 Redis Key
*/
private String code;
/**
* 中文描述
*/
private String name;
/**
* 延迟队列具体业务实现的 Bean
* 可通过 Spring 的上下文获取
*/
private String beanId;
}
4.延迟队列执行器
/**
* @author yhh
* @Description: 延迟队列执行器
* @date 2022-04-21 15:10
*/
public interface RedisDelayQueueHandle<T> {
void execute(T t);
}
5.延迟队列工具
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* @author yhh
* @Description: 延迟队列工具
* @date 2022-04-21 15:13
*/
@Slf4j
@Component
public class RedisDelayQueueUtil {
@Autowired
private RedissonClient redissonClient;
public <T> void addDelayQueue(T value, LocalDateTime endTime, String queueCode) {
long seconds = Duration.between(LocalDateTime.now(), endTime).getSeconds();
if (seconds > 0) {
addDelayQueue(value, seconds, TimeUnit.SECONDS, queueCode);
}
}
public <T> void addDelayQueue(T value, long delay, String queueCode) {
addDelayQueue(value, delay, TimeUnit.SECONDS, queueCode);
}
/**
* 添加延迟队列
* @param value 队列值
* @param delay 延迟时间
* @param timeUnit 时间单位
* @param queueCode 队列键
* @param <T> 泛型
*/
public <T> void addDelayQueue(T value, long delay, TimeUnit timeUnit, String queueCode){
try {
RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);
RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
delayedQueue.offer(value, delay, timeUnit);
log.info("(添加延时队列成功) 队列键:{},队列值:{},延迟时间:{}", queueCode, value, timeUnit.toSeconds(delay) + "秒");
//释放队列
delayedQueue.destroy();
} catch (Exception e) {
log.error("(添加延时队列失败) {}", e.getMessage());
throw new RuntimeException("(添加延时队列失败)");
}
}
/**
* 获取延迟队列
* @param queueCode 队列主键
* @param <T> 泛型
* @return
* @throws InterruptedException
*/
public <T> T getDelayQueue(String queueCode) throws InterruptedException {
RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode);
//避免消息伪丢失(应用重启未消费),官网推荐
redissonClient.getDelayedQueue(blockingDeque) ;
T value = (T) blockingDeque.take();
return value;
}
public boolean removeDelayedQueue(@NonNull Object o, @NonNull String queueCode) {
if (StringUtils.isBlank(queueCode) || Objects.isNull(o)) {
return false;
}
try {
RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);
RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
boolean flag = delayedQueue.remove(o);
if(flag){
log.info("(删除延时队列保证唯一性) 队列键:{},队列值:{}", queueCode, o);
}
delayedQueue.destroy();
return flag;
} catch (Exception e) {
log.error("(删除延时队列异常) 队列键:{},队列值:{},错误信息:{}",queueCode, o, e.getMessage());
throw new RuntimeException("(删除延时队列异常)");
}
}
}
6.方法中调用
@Autowired
private RedisDelayQueueUtil redisDelayQueueUtil;
//加入延迟队列失效
Long seconds = Duration.between(LocalDateTime.now(), 失效时间).getSeconds();
redisDelayQueueUtil.addDelayQueue(id, seconds, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_TIMEOUT.getCode());
//删除延迟队列
redisDelayQueueUtil.removeDelayedQueue(id, RedisDelayQueueEnum.ORDER_TIMEOUT.getCode());