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. GitHub 的 Action 接入 Stryker.NET 进行自动化测试单元测试鲁棒性

    假设有一个捣蛋的小伙伴加入了你的团队,这个捣蛋的小伙伴喜欢乱改代码,请问此时的单元测试能否拦住这些逗比行为?如果不能拦住逗比行为,是否代表着单元测试有所欠缺,或者有某些分支逻辑没有考虑到.本文将告诉大 ...

  2. kubeadm搭建单master多node节点的k8s集群(3)

    一.实验环境准备 K8s集群角色 IP 主机名 安装的组件 配置 控制节点 192.168.1.10 master apiserver.controller-manager.scheduler.etc ...

  3. 利用PostMan 模拟上传/下载文件

    我们经常用postman模拟各种http请求.但是有时候因为业务需要,我们需要测试上传下载功能.其实postman也是很好支持这两种操作的. 一.上传文件: 1.打开postman 选择对应reque ...

  4. 如何修改npm包源码后,重新npm包的时候能是修改后的版本

    肯定是clone一份到gitHub啦 保存一份修改后的npm包到自己的私有库 npm 安装 git 仓库的方式 npm install <git remote url> 例如 npm in ...

  5. 🔥架构师狂掉1024根头发,总算搞定SSL通配证书

    架构师狂掉1024根头发,总算搞定SSL通配证书 经过许多个日日夜夜的持续开发(掉了1024根头发),总算搞定了v1.11.0版本,修复和解决了许多问题,也支持CDN和OSS证书的部署. v1.11. ...

  6. AIRIOT答疑第7期|如何快速提升物联网项目交付速度?

    平台+模板,套上就能用!贼拉快! AIRIOT提供物联网低代码平台+多套行业案例模板,针对于有明确项目的服务商,用平台已经配置好的节点数.功能模块.流程,直接上手干项目! AIRIOT解答: 多套物联 ...

  7. aws语音呼叫调用,告警电话

    import requests data = { 'channel': '99x', 'called_number': '135xxx', 'tts_code': 'TTS_xx', 'tts_par ...

  8. pytorch(GPU版)安装

    确认有无英伟达显卡,有才能安装GPU版的pytorch,否则只能装CPU版 1.任务管理器->性能: 设备管理器->显示适配器,也可以: nvidia驱动安装地址(大部分电脑自带,不需要额 ...

  9. Java中CAS算法的集中体现:Atomic原子类库,你了解吗?

    一.写在开头 在前面的博文中我们学习了volatile关键字,知道了它可以保证有序性和可见性,但无法保障原子性,结局原子性问题推荐使用synchronized.Lock或者AtomicInteger: ...

  10. Java面试题:SpringBoot异常捕获,让程序“免疫”一切错误!

    在Spring Boot应用程序中,捕获全局异常是一个重要的方面,它可以帮助我们处理在应用程序运行时可能发生的各种错误情况.通过适当地捕获和处理这些异常,我们可以改善用户体验并及时采取必要的措施. 使 ...