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实现定时任务测试的更多相关文章

  1. 基于SpringBoot实现定时任务的设置(常用:定时清理数据库)

    1.构建SpringBoot工程项目 1)创建一个Springboot工程,在它的程序入口加上@EnableScheduling,开启调度任务. @SpringBootApplication @Ena ...

  2. 玩转SpringBoot之定时任务详解

    序言 使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式: 一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer) 前者相信大家都很熟悉, ...

  3. SpringBoot整合定时任务和异步任务处理 3节课

    1.SpringBoot定时任务schedule讲解   定时任务应用场景: 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类        ...

  4. SpringBoot整合定时任务和异步任务处理

    SpringBoot定时任务schedule讲解 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 timer:配置比较麻烦,时间延后问题, ...

  5. springboot实现定时任务的方式

    springboot实现定时任务的方式 a   Timer:这是java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务.使用这种方式可以让你的程 ...

  6. 记一次Redis和NetMQ的测试

    Redis是一个高速缓存K-V数据库,而NetMQ是ZeroMQ的C#实现版本,两者是完全不同的东西. 最近做游戏服务器的时候想到,如果选择一个组件来做服务器间通信的话,ZeroMQ绝对是一个不错的选 ...

  7. redis实现主从复制-单机测试

    一.redis实现主从复制-单机测试1.安装redis tar -zxvf redis-2.8.4.tar.gzcd redis-2.8.4make && make install2. ...

  8. Redis介绍及Jedis测试

    1.Redis简介 Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库.缓存和消息中间件. 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes ...

  9. SpringBoot 配置定时任务

    SpringBoot启用定时任务,其内部集成了成熟的框架,因此我们可以很简单的使用它. 开启定时任务 @SpringBootApplication //设置扫描的组件的包 @ComponentScan ...

  10. SpringBoot - 添加定时任务

    SpringBoot 添加定时任务 EXample1: import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spri ...

随机推荐

  1. WPF 如何获取有哪些 VisualBrush 用了某个控件

    我写了一个特殊的控件,我期望了解到有哪些 VisualBrush 捕获了此控件,或者说有哪些 VisualBrush 用了此控件的界面 本文的方法需要用到反射,需要使用 WPF 框架里面没有公开的字段 ...

  2. Jenkins 简述及其搭建

    什么是持续集成? 持续集成(CI)是在软件开发过程中自动化和集成许多团队成员的代码更改和更新的过程.在 CI 中,自动化工具在集成之前确认软件代码是有效且无错误的,这有助于检测错误并加快新版本的发布. ...

  3. SpringBoot实现WebSocket发送接收消息 + Vue实现SocketJs接收发送消息

    SpringBoot实现WebSocket发送接收消息 + Vue实现SocketJs接收发送消息 参考: 1.https://www.mchweb.net/index.php/dev/887.htm ...

  4. Splashtop 扩展了所有 Android 8.0 以上设备的远程控制功能

    好消息:Splashtop远程访问和远程支持软件现在支持100多个品牌的 Android 设备. 2020年9月15日,远程访问和远程支持解决方案的全球领导者 Splashtop Inc. 宣布:所有 ...

  5. 密码学—仿射密码Python程序

    文章目录 仿射密码 加密算法 解密算法 仿射密码 古典密码,且属于单表加密. 加密算法 仿射密码公式 c = m×k + b mod 26 c是密文,m是明文,m作为26字母中的明文,因此计算出来的密 ...

  6. kubernetes 之 Rolling Update 滚动升级

    滚动升级 1.错误的yml文件 [machangwei@mcwk8s-master ~]$ cat mcwHttpd.yml apiVersion: apps/v1 kind: Deployment ...

  7. webapi动态创建后台任务(使用排队的后台任务)

    很多时候我们都会使用后台定时任务,但有些任务不需要定时执行,只需要请求到来时执行一次,比如请求服务器到某个地方同步数据,但请求不需要等数据同步完成再响应.这时候就可以使用排队的后台任务. 基本原理是用 ...

  8. Java21 GA新特性-虚拟线程详解

    本文转载至:虚拟线程 - VirtualThread源码透视 - throwable - 博客园 (cnblogs.com) 一. 前提 JDK19于2022-09-20发布GA版本,该版本提供了虚拟 ...

  9. Pandas学习之路【3】

    新增列的一些操作 1.新增一个列,直接给列赋值 # 取所有行,新增的列为new_col df.loc[:, 'new_col'] = 100 2.使用df.apply方法给新增的列赋值 def get ...

  10. CSS——阴影

    <!DOCTYPE html> <html> <head> <style> p.one { text-shadow: 3px 5px 5px #FF00 ...