摘要:
1. 使用Redis的过期策略Redis本身支持键的过期策略,你可以设置订单键(例如使用订单ID作为键)的过期时间,当时间到达后,Redis会自动删除该键。然后,你可以在Sprin... 1. 使用Redis的过期策略
Redis本身支持键的过期策略,你可以设置订单键(例如使用订单ID作为键)的过期时间,当时间到达后,Redis会自动删除该键。然后,你可以在Spring Boot应用中监听这些删除事件,从而触发订单取消的逻辑
maven引入springboot集成的redis依赖
org.springframework.bootspring-boot-starter-data-redis
2.对redis进行配置
package com.sl.config;
import com.sl.item.sys.service.SysFileManageService;
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.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
/**
* 创建redis提供的过消息监听适配器
* @param sysFileManageService 当目标消息被触发,通过反射调用的自定义服务类
* @return redis消息监听适配器
*/
@Bean
public MessageListenerAdapter listenerAdapter(SysFileManageService sysFileManageService) {
return new MessageListenerAdapter(sysFileManageService, "onRedisInspectFileExpired");
}
/**
* 接收来自 Redis 频道的消息,并驱动注入其中的 MessageListener 实例
* @param connectionFactory rendis消息连接对象
* @param listenerAdapter 消息监听适配器
* @return 创建接收Redis频道消息
*/
@Bean
public RedisMessageListenerContainer container(LettuceConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("__keyevent@0__:expired"));
return container;
}
/**
* redis序列化的工具配置类,下面这个请一定开启配置
* 127.0.0.1:6379 keys *
* 1)"ord:102" 序列化过
* 2)"\xac\xed\x00\x05t\ord:102" 没有序列化过
* this.redisTemplate.opsForValue()//提供了操作String类型的所有方法
* this.redisTemplate.opsForList()//提供了操作List类型的所有方法
* this.redisTemplate.opsForSet()//提供了操作Set类型的所有方法
* this.redisTemplate.opsForHash()//提供了操作Hash类型的所有方法
* this.redisTemplate.opsForZSet()//提供了操作ZSet类型的所有方法
*
*
* @param
* @return
*/
@Autowired
private RedisTemplate redisTemplate;
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
}然后在你定义的SysFileManageService服务类实现onRedisInspectFileExpired方法
3.在redis组件中redis.conf开启监听Redis键的删除事件:
使用Redis的keyspace notifications功能。首先,需要在Redis配置中启用此功能 将notify-keyspace-events 设置为Ex
notify-keyspace-events Ex
至此,整个逻辑走到闭环!




