使用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 C# 如果在构造函数抛出异常 析构函数是否会执行
假设在某个类型的构造函数里面抛出了异常,那么这个对象的析构函数是否会执行 如下面代码 private void F1() { try { _ = new Foo(); } catch { // 忽略 ...
- 实践探讨Python如何进行异常处理与日志记录
本文分享自华为云社区<Python异常处理与日志记录构建稳健可靠的应用>,作者:柠檬味拥抱. 异常处理和日志记录是编写可靠且易于维护的软件应用程序中至关重要的组成部分.Python提供了强 ...
- k8s应用---持久化存储和StorageClass(10)
一.简介: 在 k8s 中为什么要做持久化存储? 在 k8s 中部署的应用都是以 pod 容器的形式运行的,假如我们部署 MySQL.Redis 等数据库,需要 对这些数据库产生的数据做备份.因为 P ...
- K8s控制器---Replicaset(7)
一.Replicaset(目前少用了) 1.1 控制器管理pod 什么是控制器?前面我们学习了 Pod,那我们在定义 pod 资源时,可以直接创建一个 kind:Pod 类型的自主式 pod,但是这存 ...
- SpringBoot项目预加载数据——ApplicationRunner、CommandLineRunner、InitializingBean 、@PostConstruct区别
0.参考.业务需求 参考: https://www.cnblogs.com/java-chen-hao/p/11835120.html#_label1 https://zhuanlan.zhihu.c ...
- 【LGR-170-Div.3】洛谷基础赛 #6 & Cfz Round 3 & Caféforces #2
这套题感觉质量很高,思维含量大概div.2? A.Battle \[x \equiv r(\bmod P) \] \[P \mid x - r \] 因此只有第一次操作是有效的. void solve ...
- [Cmake Qt]找不到文件ui_xx.h的问题?有关Qt工程的问题,看这篇文章就行了。
前言 最近在开发一个组件,但是这个东西是以dll的形式发布的界面库,所以在开发的时候就需要上层调用. 如果你是很懂CMake的话,ui_xx.h的文件目录在 $ 下 然后除了有关这个ui_xx.h,还 ...
- ls的输出格式
在Linux中,如果在一个目录下面执行ls -al命令,输出格式如下: ls -al总共输出7列,下面对每一列进行说明. 第一列表示这个文件的权限与类型,它总共有10位,每个位的作用如下图所示: 其中 ...
- list转json tree的工具类
package com.glodon.safety.contingency.job; import com.alibaba.fastjson.JSON; import com.alibaba.fast ...
- .NET实现获取NTP服务器时间并同步(附带Windows系统启用NTP服务功能)
对某个远程服务器启用和设置NTP服务(Windows系统) 打开注册表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Tim ...