使用Redis完成定时任务
应用场景:在订单业务中,有时候需要对订单设置有效期,有效期到了后如果还未支付,就需要修改订单状态;
与设备进行长链接,如果一段时间内没有收到设备发送的心跳,则修改状态
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、修改boot的redis配置
spring:
#redis
redis:
database: 0
host: 127.0.0.1
password: redis_123456
port: 6379
3、在服务器中 修改redis.conf配置文件(原来notify-keyspace-events 属性是" " 空的,我们只需要填上“Ex”就行了)(这个配置可以省略)
notify-keyspace-events "Ex"
4、创建一个Redis监控类,用于监控过期的key,该类需继承KeyExpirationEventMessageListener
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer; import java.nio.charset.StandardCharsets; /**
* @program: SpringCloud
* @description: redis Key过期监听
* @author: zhang yi
* @create: 2020-03-24 14:14
*/
public class KeyExpiredListener extends KeyExpirationEventMessageListener { public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
} @Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("过期key:" + message.toString());
}
}
5、创建Redis配置类
import com.zy.rabbitmq.base.Listener.KeyExpiredListener;
import org.springframework.beans.factory.annotation.Autowired;
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; /**
* @program: SpringCloud
* @description: redis配置类
* @author: zhang yi
* @create: 2020-03-24 14:17
*/
@Configuration
public class RedisConfiguration { @Autowired
private RedisConnectionFactory redisConnectionFactory; @Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
return redisMessageListenerContainer;
} @Bean
public KeyExpiredListener keyExpiredListener() {
return new KeyExpiredListener(this.redisMessageListenerContainer());
} }
6、这里提供一个redis工具类,用于存储值,获取值,获取过期时间等操作。
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* redis 工具类
* @Author ZhangYi
*/
@Component
public class RedisUtil { @Resource
private RedisTemplate<String, Object> redisTemplate; /**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
} /**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
} // ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
} /**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} } /**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
原文地址https://blog.csdn.net/qq_39648029/article/details/105072079
使用Redis完成定时任务的更多相关文章
- 与你相遇好幸运,使用redis设置定时任务
参考链接: Nodejs中使用Redis来完成定时任务 自己在 window 7下编码实现: 1 > 首先查看redis版本: redis-server -v , 版本要求大于等于2.8 2&g ...
- flask+apscheduler+redis实现定时任务持久化
在我们开发flask的时候,我们会结合apscheduler实现定时任务,我们部署到服务器上,会不会遇到这样的问题,每次我们部署后,我们重启服务后,原来的定时任务都需要重启,这样对我们经常迭代的项目肯 ...
- [Redis]处理定时任务的2种思路
用redis完成类似 at 命令的功能,例如订单24小时后没有支付自动关闭,定时发邮件,主要说下任务生成之后怎么触发消费. 使用 有序集合 思路: 使用sorted Sets的自动排序, key 为任 ...
- django使用celery搭配redis配置定时任务
已经安装环境: Python3.6 django==2.1.8(用2.2.2需要升级sqlite3) 项目名称:ceshiproject APP名称:ceshi 第一步:centos7下首先安装r ...
- redis写定时任务获取root权限
前提: 1.redis由root用户启动. 2.开启cron的时候,/var/spool/cron linux机器下默认的计划任务,linux会定时去执行里面的任务. 启动服务 :/sbin/serv ...
- 分布式锁 基于Redis
分布式锁的实现(基于Redis) 参考:http://www.jb51.net/article/75439.htm http://www.linuxidc.com/Linux/2015-01/1118 ...
- redis之线程IO模型
非阻塞 IO 当我们调用套接字的读写方法,默认它们是阻塞的,比如 read 方法要传递进去一个参数n,表示读取这么多字节后再返回,如果没有读够线程就会卡在那里,直到新的数据到来或者连接关闭了,read ...
- 两种Redis持久化原理的详解
Redis为持久化提供了两种方式: RDB:在指定的时间间隔能对你的数据进行快照存储. AOF:记录每次对服务器写的操作,当服务器重启的时候会重新执行这些命令来恢复原始的数据. 本文将通过下面内容的介 ...
- Redis 键空间事件通知
出处: 使用Redis完成定时任务 场景 使用Java做过项目的人大概都用过定时器.一般来说,项目里订单模块和评论模块,都会涉及到定时任务执行.比如说: 用户下订单后,需要在5分钟内完成支付,否则 ...
随机推荐
- Java安全之Spring内存马
Java安全之Spring内存马 基础知识 Bean bean 是 Spring 框架的一个核心概念,它是构成应用程序的主干,并且是由 Spring IoC 容器负责实例化.配置.组装和管理的对象. ...
- UVA 156 Ananagrams (STL multimap & set)
原题链接: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&p ...
- Appium+python自动化测试过程中问题
一.自动删除contactmanager 自动化测试appium提供的sample如下包/activity:com.example.android.contactmanager/.ContactMan ...
- Go语言测试:testing
学习参考来源:https://www.liwenzhou.com/posts/Go/16_test/ go test工具 必须导入包: import "testing" go te ...
- [C语言基础] 数组与指针之间的引用
通过指针引用数组,通过数组引用指针,你搞明白了么?通过下面3种情形来了解一下数组和指针 Case 1. unsigned char arry[10]; unsigned char *ptr; unsi ...
- gin框架中的同步异步
goroutine机制可以方便地实现异步处理 另外,在启动新的goroutine时,不应该使用原始上下文,必须使用它的只读副本 // 异步 func longAsync(context *gin.Co ...
- kubernetes之kubeadm 安装kubernetes 高可用集群
1. 架构信息 系统版本:CentOS 7.6 内核:3.10.0-957.el7.x86_64 Kubernetes: v1.14.1 Docker-ce: 18.09.5 推荐硬件配置:4核8G ...
- Airtest 的连接安卓模拟器
1. 开启安卓模拟器 2. 查看进程,MEmuHeadless.exe的进行程号, 然后在cmd中输入 netstat -ano|findstr "16116" 3. 到 airt ...
- chapter3——逻辑回归手动+sklean版本
1 导入numpy包 import numpy as np 2 sigmoid函数 def sigmoid(x): return 1/(1+np.exp(-x)) demox = np.array([ ...
- .NET Core分析程序集最优美的方法,不用Assembly.LoadFile(),超越ReflectionOnlyLoad
在编写.NET程序的时候,如果需要对一个程序集文件进行分析,我们可以使用Assembly.LoadFile()来加载这个程序集,然后对LoadFile()方法返回的Assembly对象进行进一步的分析 ...