使用Redis+SpringBoot实现定时任务测试
Redis实现定时任务是基于对RedisKey值的监控
具体代码实现:
代码GitHub地址:https://github.com/Tom-shushu/Project
- 建一个SpringBoot项目
- 引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>redistask</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>redistask</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 配置文件
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.timeout=10000
- 新建一个配置类
package com.zhouhong.redistask.redistaskconfig; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer; /**
* description: Redis配置类
* @author: zhouhong
* @version: V1.0.0
* @date: 2021年3月19日 上午10:58:24
*/
@Configuration
public class RedisTaskConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
- 新建Controller,设置不同过期时间的Key值,注意这里key值最好使用当前的业务标识做前缀,不然可能出现key重复的现象。
package com.zhouhong.redistask.redistaskcontroller; import java.util.Date;
import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; /**
* description: 测试Redis定时Controller类
* @author: zhouhong
* @version: V1.0.0
* @date: 2021年3月19日 上午10:59:21
*/ @RestController
public class RedisTaskController { @Autowired
private RedisTemplate< String, String> template;
Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
/**
* 设置定时key,这里key最好使用业务前缀,防止名字相同
* @return
*/
@RequestMapping(value = "putkeys", method = RequestMethod.POST)
public String putRedisTaskKeys() {
Date date = new Date();
logger.info("业务开始时间:" + date);
String key10S = "business1"+"|"+"key10S"+"|"+"其他业务中需要使用到的参数";
String key20S = "business1"+"|"+"key20S"+"|"+"其他业务中需要使用到的参数";
template.opsForValue().set(key10S, "values", 10, TimeUnit.SECONDS);
template.opsForValue().set(key20S, "values", 20, TimeUnit.SECONDS);
return "RedisKey过期键设置成功";
} }
- 新建Service用来监控过期Key,并且针对不同时间做不同的业务
package com.zhouhong.redistask.service; import java.util.Date; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
* description: RedisKey键监听以及业务逻辑处理
* @author: zhouhong
* @version: V1.0.0
* @date: 2021年3月19日 上午10:58:52
*/
@Service
@Component
public class RedisTaskService extends KeyExpirationEventMessageListener { Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
/**
* @param listenerContainer
*/
public RedisTaskService(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = message.toString();
// 将拿到的过期键使用之前拼接时的特殊符号分割成字符数组
String[] expiredKeyArr = expiredKey.split("\\|");
String businessSign = expiredKeyArr[0].toString();
String expiredTimeSign = expiredKeyArr[1].toString();
String othersParm = expiredKeyArr[2].toString(); logger.info(businessSign + expiredTimeSign + othersParm);
Date date = new Date();
// 只有本业务才执行以下操作
if (businessSign.equals("business1")) {
if (expiredTimeSign.equals("key10S")) {
// 定时十秒钟后业务处理
logger.info("十秒钟时的时间:"+ date);
logger.info("定时任务10秒钟已到,下面处理相关业务逻辑代码!!!");
logger.info("10秒钟后的业务逻辑代码,其他业务参数" + othersParm);
} else if (expiredTimeSign.equals("key20S")) {
// 定时十秒钟后业务处理
logger.info("二十秒钟时的时间:"+ date);
logger.info("定时任务20秒钟已到,下面处理相关业务逻辑代码!!!");
logger.info("20秒钟后的业务逻辑代码,其他业务参数" + othersParm);
}
} else {
logger.error("非business1业务不做处理");
}
}
}
- 演示:

定时成功!!
使用Redis+SpringBoot实现定时任务测试的更多相关文章
- 基于SpringBoot实现定时任务的设置(常用:定时清理数据库)
1.构建SpringBoot工程项目 1)创建一个Springboot工程,在它的程序入口加上@EnableScheduling,开启调度任务. @SpringBootApplication @Ena ...
- 玩转SpringBoot之定时任务详解
序言 使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式: 一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer) 前者相信大家都很熟悉, ...
- SpringBoot整合定时任务和异步任务处理 3节课
1.SpringBoot定时任务schedule讲解 定时任务应用场景: 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 ...
- SpringBoot整合定时任务和异步任务处理
SpringBoot定时任务schedule讲解 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 timer:配置比较麻烦,时间延后问题, ...
- springboot实现定时任务的方式
springboot实现定时任务的方式 a Timer:这是java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务.使用这种方式可以让你的程 ...
- 记一次Redis和NetMQ的测试
Redis是一个高速缓存K-V数据库,而NetMQ是ZeroMQ的C#实现版本,两者是完全不同的东西. 最近做游戏服务器的时候想到,如果选择一个组件来做服务器间通信的话,ZeroMQ绝对是一个不错的选 ...
- redis实现主从复制-单机测试
一.redis实现主从复制-单机测试1.安装redis tar -zxvf redis-2.8.4.tar.gzcd redis-2.8.4make && make install2. ...
- Redis介绍及Jedis测试
1.Redis简介 Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库.缓存和消息中间件. 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes ...
- SpringBoot 配置定时任务
SpringBoot启用定时任务,其内部集成了成熟的框架,因此我们可以很简单的使用它. 开启定时任务 @SpringBootApplication //设置扫描的组件的包 @ComponentScan ...
- SpringBoot - 添加定时任务
SpringBoot 添加定时任务 EXample1: import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spri ...
随机推荐
- dotnet OpenXML 读取 PPT 形状边框定义在 Style 的颜色画刷
本文来和大家聊聊在 PPT 形状使用了 Style 样式的颜色画刷读取方法 在开始之前,期望大家已了解如何在 dotnet 应用里面读取 PPT 文件,如果还不了解读取方法,请参阅 C# dotnet ...
- dotnet 使用 FormatterServices 的 GetUninitializedObject 方法在丢失 DLL 情况下能否执行
在 dotnet 里面,可以使用 FormatterServices 的 GetUninitializedObject 方法可以实现只创建对象,而不调用对象的构造函数方法.而如果在使用此方法时,存在了 ...
- docker容器资源配额
1.docker 容器控制CPU docker通过cgroup来控制容器使用的资源限制,可以对docker限制的资源包括cpu.内存.磁盘 1.1 指定docker容器可以使用的cpu份额 # 查看配 ...
- .NET Aspire 预览版 6 发布
.NET Aspire 预览版 6 引入了一系列重大更新,主要包括 API 的重大更改.安全性和可靠性的提升.新的资源和组件.应用程序主机的更新.测试支持.模板更新.组件更新.Azure 配置包的更新 ...
- vue+element设置选择日期最大范围(普通版)
效果是只能跟当天时间有关(30天),下一篇将来的任意时段,比较符合实际 <!DOCTYPE html> <html> <head> <meta charset ...
- EXCEL-统计sheet个数、统计指定单元格个数
Excel的函数,可以直接在里面执行 1.统计sheet个数 =SHEETS() 参考:https://office.tqzw.net.cn/excel/excel/8168.html 2.统计单元格 ...
- 六、Doris数据流与控制流
目录: 数据查询 数据导入 元数据修改 1.查询 用户可使用MySQL客户端连接FE,执行SQL查询, 获得结果,查询流程如下: 分步说明: ① MySQL客户端执行DQL SQL命令. ② FE解析 ...
- .NET 缓存:内存缓存 IMemoryCache、分布式缓存 IDistributedCache(Redis)
.NET缓存里分了几类,主要学习内存缓存.分布式缓存 一.内存缓存 IMemoryCache 1.Program注入缓存 builder.Services.AddMemoryCache(); 2.相关 ...
- flask注册功能
一个项目的简单结构划分 首先创建一个新项目 可以正常运行与访问 创建配置文件并添加配置. 将这里拆分到不同的文件中,让启动文件更加简洁. 创建一个apps包,导入配置模块,导入Flask,定义创建ap ...
- 【C# mvc5】使用mvc5 +bootstrap+EF6搭建一个权限管理系统的心得体会
使用mvc5的体会,是 业务代码都可以独立分层,比如搭配多层架构,通过controller控制器传递需要渲染的列表,按钮.接受前端返回的实体模型等.总之我觉得要在前端渲染的数据可以写在controll ...