redis数据到期监听

在项目中用了redis缓存,缓存的是数据需要设置一个过期时间

1 、首先把数据存如redis并添加失效时间:

public ResultUtil saveDelayEvent(EventInfo info){
    try {
        Map map = new HashMap<>();
        map.put("eventInfo",info);
        Date date = new Date();
        long interval = (info.getDelayDate().getTime() - date.getTime())/1000;
        System.out.println("两个时间相差"+interval+"秒");
        stringRedisTemplate.opsForValue().set("event_" +info.getId(), map.toString(), interval, TimeUnit.SECONDS);
        return ResultUtil.Ok("保存成功");
    }catch (Exception e){
        e.printStackTrace();
        return ResultUtil.Faild("保存失败");
    }

}

redis数据到期监听_第1张图片

2、设置失效时间后,要在数据失效的时候监听到,然后再次存入或者做别的操作

/**
 * redis监听
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {



    @Autowired
    private EventInfoTaskDao eventInfoTaskDao;

    @Autowired
    private MessageAPIService messageApi;

    private final String EXCHANGE = "openOne_event";



    /**
     * Creates new {@link } for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件,进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获得失效的key
        String expiredKey = message.toString();
        if(expiredKey.contains("event_")){
            String eventId = expiredKey.substring(6, expiredKey.length());
            List task = eventInfoTaskDao.getTask(null, eventId);
            JSONArray json = new JSONArray();
            json.add(task);
            messageApi.sendMessage(EXCHANGE,eventId,json.toJSONString());

        }

    }

另外需要注入bean:

@Configuration
@EnableCaching
@ConditionalOnBean(RedisCacheManager.class)
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
   RedisTemplate redisTemplate = new RedisTemplate<>();

   // 配置连接工厂
   redisTemplate.setConnectionFactory(redisConnectionFactory);

   // 使用自定义 fastjson 序列化, 作为 value 值序列化 FastJsonRedisSerializer
   FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);

   redisTemplate.setValueSerializer(fastJsonRedisSerializer);
   redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);

   // 使用 StringRedisSerializer 作为 key 的序列化
   redisTemplate.setKeySerializer(new StringRedisSerializer());
   redisTemplate.setHashKeySerializer(new StringRedisSerializer());

   return redisTemplate;
} 
  

 

@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {

   RedisMessageListenerContainer container = new RedisMessageListenerContainer();
   container.setConnectionFactory(connectionFactory);
   return container;
}
}

你可能感兴趣的:(redis)