redis实现mq的任务功能 Evergreen 2021年05月20日 实战技巧 预计阅读 1 分钟 1.引入依赖包 ```java org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 ${commons-pool2.version} ``` 2.springboot配置文件配置redis相关。注意:这里的时间`一定要配置为0ms`,否则redis在获取队列数据时,如果没有入队数据,会返回超时。0ms就是阻塞获取,直到有数据。 ```yml spring: redis: database: 0 host: port: # 链接超时时间 单位 ms(毫秒) timeout: 0 commandTimeout: 5000 ``` 3.编写消费端任务线程方法 ```java @Slf4j @Component public class TaskExecutor extends Thread { @Autowired protected RedisTemplate redisTemplate; private volatile int index = 0; @Override public void run() { while (true){ String result = (String)redisTemplate.opsForList().rightPop("test_mq_pop", 0, TimeUnit.SECONDS); if(result!=null){ index++; log.info("第【{}】次,消费端消费数据:[{}]",index,result); } } } } ``` 4.编写在springboot启动后开启线程执行 ```java @Component public class TaskExecutorStart implements CommandLineRunner { @Autowired TaskExecutor taskExecutor; @Override public void run(String... args) throws Exception { taskExecutor.start(); } } ``` 5.编写生产端通过http调用生产数据 ```java @RequestMapping(value = "/thread", method = RequestMethod.GET) public Result test(@RequestParam("param") String param) { redisTemplate.opsForList().leftPush("test_mq_pop", param); return Result.success(); } ```
评论区