当前位置:   article > 正文

Redis过期回调_error org.springframework.data.redis.listener.redi

error org.springframework.data.redis.listener.redismessagelistenercontainer

       没学过redis,被要求做一个文件上传10秒超时的需求,一开始以为难的很,当了解了redis的回调机制,真的很简单!!!!

  1. package cn.cge.main.config;
  2. import cn.cge.track.entity.TrackProcessEnum;
  3. import cn.cge.track.service.TrackService;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.redis.connection.Message;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
  10. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  11. import org.springframework.stereotype.Component;
  12. import org.springframework.web.client.RestTemplate;
  13. @Component
  14. public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
  15. private final static Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);
  16. public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
  17. super(listenerContainer);
  18. }
  19. @Autowired
  20. private RedisTemplate redisTemplate;
  21. @Autowired
  22. private TrackService trackService;
  23. @Override
  24. public void onMessage(Message message, byte[] pattern) {
  25. try {
  26. String expiredKey = message.toString();//获取所有key
  27. //以下是你想执行的代码逻辑
  28. if(expiredKey.endsWith("_upload!!!")){
  29. System.out.print("我想输出这句话")
  30. }
  31. }catch (Exception e){
  32. e.printStackTrace();
  33. }
  34. }
  35. }
  1. package cn.cge.main.config;
  2. /**
  3. * 这一段直接复制,写死的
  4. **/
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.connection.RedisConnectionFactory;
  8. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  9. @Configuration
  10. public class RedisListenerConfig {
  11. @Bean
  12. RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
  13. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  14. container.setConnectionFactory(connectionFactory);
  15. return container;
  16. }
  17. }

下面是自己写的代码:

  1. String uploadKey = "这是自定义的key_upload!!!";
  2. //插入缓存
  3. redisTemplate.opsForValue().set(uploadKey,"这是值!");
  4. //设置缓存过期时间为10秒
  5. redisTemplate。expire(uploadkey,10,TimeUnit.SECOUNDS);
  6. //当缓存过期,就会自动执行第一段代码块中的逻辑代码,因为key结尾是_upload!!!,其他的不影响!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/685112
推荐阅读
相关标签
  

闽ICP备14008679号