前言:在工作开发中很多需求都需要用到定时任务,但是市面上多半都是轮询或者固定时间执行的开源工具,我之前写过一次基于quartz的定时任务,前端和分布式还需要完善 https://my.oschina.net/wangnian/blog/758054 ,编程式传入一个时间,到点就会按照事先配置好的执行。今天工作中又遇到了类似的需求,没有完善拿不出手,所以简单的封装一下redisson的API,只需要简单的传入间隔时间就可以了。
这个没有啥理论知识,就是对于redisson的delayedQueue延迟队列的封装,接下来直接粘贴代码,有需要的直接复制过去用,没需要的可以看看我的代码指指毛病。
1.导入redisson包
注意,如果是Springboot的项目强制使用,别单独引入redisson的jar包,再自己配置config
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.10.5</version> </dependency>
2.用上面的包直接配置SpringBootRedis标准就可以
spring.redis.host=192.168.1.100 spring.redis.port=6379
3.新增一个启动项目时候就开启监听类RedisDelayedQueueInit
package com.test.redis.demo;
import com.alibaba.fastjson.JSON;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 初始化队列监听
*/
@Component
public class RedisDelayedQueueInit implements ApplicationContextAware {
private static Logger logger = LoggerFactory.getLogger(RedisDelayedQueueInit.class);
@Autowired
RedissonClient redissonClient;
/**
* 获取应用上下文并获取相应的接口实现类
*
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, RedisDelayedQueueListener> map = applicationContext.getBeansOfType(RedisDelayedQueueListener.class);
for (Map.Entry<String, RedisDelayedQueueListener> taskEventListenerEntry : map.entrySet()) {
String listenerName = taskEventListenerEntry.getValue().getClass().getName();
startThread(listenerName, taskEventListenerEntry.getValue());
}
}
/**
* 启动线程获取队列*
*
* @param queueName queueName
* @param redisDelayedQueueListener 任务回调监听
* @param <T> 泛型
* @return
*/
private <T> void startThread(String queueName, RedisDelayedQueueListener redisDelayedQueueListener) {
RBlockingQueue<T> blockingFairQueue = redissonClient.getBlockingQueue(queueName);
//由于此线程需要常驻,可以新建线程,不用交给线程池管理
Thread thread = new Thread(() -> {
logger.info("启动监听队列线程" + queueName);
while (true) {
try {
T t = blockingFairQueue.take();
logger.info("监听队列线程{},获取到值:{}", queueName, JSON.toJSONString(t));
new Thread(() -> {
redisDelayedQueueListener.invoke(t);
}).start();
} catch (Exception e) {
logger.info("监听队列线程错误,", e);
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
}
}
});
thread.setName(queueName);
thread.start();
}
}
4.新建一个接口RedisDelayedQueueListener
package com.test.redis.demo;
/**
* 队列事件监听接口,需要实现这个方法
*
* @param <T>
*/
public interface RedisDelayedQueueListener<T> {
/**
* 执行方法
*
* @param t
*/
void invoke(T t);
}
5.新增任务工具类
package com.test.redis.demo;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisDelayedQueue {
@Autowired
RedissonClient redissonClient;
private static Logger logger = LoggerFactory.getLogger(RedisDelayedQueue.class);
/**
* 添加队列
*
* @param t DTO传输类
* @param delay 时间数量
* @param timeUnit 时间单位
* @param <T> 泛型
*/
public <T> void addQueue(T t, long delay, TimeUnit timeUnit, String queueName) {
logger.info("添加队列{},delay:{},timeUnit:{}" + queueName, delay, timeUnit);
RBlockingQueue<T> blockingFairQueue = redissonClient.getBlockingQueue(queueName);
RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
delayedQueue.offer(t, delay, timeUnit);
}
}
4.然后就可以运行并测试
新建自己的监听类继承上面的接口
package com.test.redis.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* 监听器
*/
@Component
public class TestListener implements RedisDelayedQueueListener<TaskBodyDTO> {
Logger logger = LoggerFactory.getLogger(TestListener.class);
@Override
public void invoke(TaskBodyDTO taskBodyDTO) {
//这里调用你延迟之后的代码
logger.info("执行...." + taskBodyDTO.getBody() + "===" + taskBodyDTO.getName());
}
}
新增DTO
package com.test.redis.demo;
import java.io.Serializable;
public class TaskBodyDTO implements Serializable {
private String name;
private String body;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
运行测试
@Override
public void run(String... args) throws Exception {
TaskBodyDTO taskBody = new TaskBodyDTO();
taskBody.setBody("测试DTO实体类的BODY,3秒之后执行");
taskBody.setName("测试DTO实体类的姓名,3秒之后执行");
//添加队列3秒之后执行
redisDelayedQueue.addQueue(taskBody, 10, TimeUnit.SECONDS, TestListener.class.getName());
taskBody.setBody("测试DTO实体类的BODY,10秒之后执行");
taskBody.setName("测试DTO实体类的姓名,10秒之后执行");
//添加队列10秒之后执行
redisDelayedQueue.addQueue(taskBody, 20, TimeUnit.SECONDS, TestListener.class.getName());
taskBody.setBody("测试DTO实体类的BODY,20秒之后执行");
taskBody.setName("测试DTO实体类的姓名,20秒之后执行");
//添加队列20秒之后执行
redisDelayedQueue.addQueue(taskBody, 30, TimeUnit.SECONDS, TestListener.class.getName());
}
打印的值
2020-02-17 13:45:08.371 INFO 14700 --- [ main] com.test.redis.demo.DemoApplication : 执行....测试DTO实体类的BODY,3秒之后执行===测试DTO实体类的姓名,3秒之后执行
2020-02-17 13:45:15.467 INFO 14700 --- [ main] com.test.redis.demo.DemoApplication : 执行....测试DTO实体类的BODY,10秒之后执行===测试DTO实体类的姓名,10秒之后执行
2020-02-17 13:45:25.463 INFO 14700 --- [ main] com.test.redis.demo.DemoApplication : 执行....测试DTO实体类的BODY,20秒之后执行===测试DTO实体类的姓名,20秒之后执行
5.结束抒情环节
哈哈,说了没有啥,太简单以至于我都不好意思说,但是不封装你又不能用,嗯嗯,这样想想我的开年第一篇划水笔记还是挺棒的。对了,我这里是通过DTO的名字来区分队列名的,所以每一个定时任务的DTO都不要相同。
大家对于定时任务有其他好用的方式,或者开源的好项目,欢迎下方留言评论,我将在评论区选出100位中奖用户送出iPhone5.
哎呀,不对 我没有粉丝,等我粉丝到10000了再选中奖用户吧,哈哈