1、引入redisson
org.redisson
redisson-spring-boot-starter
3.10.5
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456
database: 12
timeout: 3000
2、创建 RedissonConfig 配置
/**
* @author: description:Redission配置类
* date: 2023年6月25日11:38:49
*/
@Slf4j
@Configuration
public class RedissionConfig {
private final String REDISSON_PREFIX = "redis://";
private final RedisProperties redisProperties;
public RedissionConfig(RedisProperties redisProperties) {
this.redisProperties = redisProperties;
}
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
String url = REDISSON_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort();
// 这里以单台redis服务器为例
config.useSingleServer()
.setAddress(url)
.setPassword(redisProperties.getPassword())
.setDatabase(redisProperties.getDatabase())
.setPingConnectionInterval(2000);
config.setLockWatchdogTimeout(10000L);
// 实际开发过程中应该为cluster或者哨兵模式,这里以cluster为例
//String[] urls = {"127.0.0.1:6379", "127.0.0.2:6379"};
//config.useClusterServers()
// .addNodeAddress(urls);
try {
return Redisson.create(config);
} catch (Exception e) {
log.error("RedissonClient init redis url:[{}], Exception:", url, e);
return null;
}
}
}
3、封装 Redis 延迟队列工具类
/**
* @author: 分布式延时队列工具类 date: 2023年6月25日11:38:34
*/
@Slf4j
@Component
@ConditionalOnBean({RedissonClient.class})
public class RedisDelayQueueUtil {
@Resource
private RedissonClient redissonClient;
/**
* 添加延迟队列
*
* @param value 队列值
* @param delay 延迟时间
* @param timeUnit 时间单位
* @param queueCode 队列键
* @param
*/
public boolean addDelayQueue(@NonNull T value, @NonNull long delay, @NonNull TimeUnit timeUnit, @NonNull String queueCode) {
if (StringUtils.isBlank(queueCode) || Objects.isNull(value)) {
return false;
}
try {
RBlockingDeque
4、创建延迟队列业务枚举
/**
* 延迟队列业务枚举
*/
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum RedisDelayQueueEnum {
ORDER_PAYMENT_TIMEOUT("ORDER_PAYMENT_TIMEOUT","订单支付超时,自动取消订单", "orderPaymentTimeout"),
ORDER_TIMEOUT_NOT_EVALUATED("ORDER_TIMEOUT_NOT_EVALUATED", "订单超时未评价,系统默认好评", "orderTimeoutNotEvaluated");
/**
* 延迟队列 Redis Key
*/
private String code;
/**
* 中文描述
*/
private String name;
/**
* 延迟队列具体业务实现的 Bean
* 可通过 Spring 的上下文获取
*/
private String beanId;
}
5、定义延迟队列执行器
/**
* 延迟队列执行器
*/
public interface RedisDelayQueueHandle {
void execute(T t);
}
6、创建枚举中定义的Bean,并实现延迟队列执行器 OrderPaymentTimeout:订单支付超时延迟队列处理类
/**
* 订单支付超时处理类
*/
@Component
@Slf4j
public class OrderPaymentTimeout implements RedisDelayQueueHandle
OrderTimeoutNotEvaluated:订单超时未评价延迟队列处理类
/**
* 订单超时未评价处理类
*/
@Component
@Slf4j
public class OrderTimeoutNotEvaluated implements RedisDelayQueueHandle
7、创建延迟队列消费线程,项目启动完成后开启
/**
* description: 启动延迟队列监测扫描
* @author:
* date: 2023年6月25日11:37:28
*/
@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {
@Autowired
private RedisDelayQueueUtil redisDelayQueueUtil;
@Autowired
private ApplicationContext context;
@Autowired
private ThreadPoolTaskExecutor ptask;
ThreadPoolExecutor executorService = new ThreadPoolExecutor(3, 5, 30, TimeUnit.SECONDS,
new LinkedBlockingQueue(1000),new ThreadFactoryBuilder().setNameFormat("order-delay-%d").build());
@Override
public void run(String... args) throws Exception {
ptask.execute(() -> {
while (true){
try {
RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
for (RedisDelayQueueEnum queueEnum : queueEnums) {
Object value = redisDelayQueueUtil.getDelayQueue(queueEnum.getCode());
if (value != null) {
RedisDelayQueueHandle redisDelayQueueHandle = (RedisDelayQueueHandle)context.getBean(queueEnum.getBeanId());
executorService.execute(() -> {redisDelayQueueHandle.execute(value);});
}
}
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
log.error("(Redission延迟队列监测异常中断) {}", e.getMessage());
}
}
});
log.info("(Redission延迟队列监测启动成功)");
}
}
以上步骤,Redis 延迟队列核心代码已经完成,下面我们写一个测试接口,用 PostMan 模拟测试一下
8、创建一个测试接口,模拟添加延迟队列
/**
* 延迟队列测试
* Created by 2023年6月25日11:37:54.
*/
@RestController
public class RedisDelayQueueController {
@Autowired
private RedisDelayQueueUtil redisDelayQueueUtil;
@PostMapping("/addQueue")
public void addQueue() {
Map map1 = new HashMap<>();
map1.put("orderId", "100");
map1.put("remark", "订单支付超时,自动取消订单");
Map map2 = new HashMap<>();
map2.put("orderId", "200");
map2.put("remark", "订单超时未评价,系统默认好评");
// 添加订单支付超时,自动取消订单延迟队列。为了测试效果,延迟10秒钟
redisDelayQueueUtil.addDelayQueue(map1, 10, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_PAYMENT_TIMEOUT.getCode());
// 订单超时未评价,系统默认好评。为了测试效果,延迟20秒钟
redisDelayQueueUtil.addDelayQueue(map2, 20, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_TIMEOUT_NOT_EVALUATED.getCode());
}
}