赞
踩
没学过redis,被要求做一个文件上传10秒超时的需求,一开始以为难的很,当了解了redis的回调机制,真的很简单!!!!
- package cn.cge.main.config;
-
- import cn.cge.track.entity.TrackProcessEnum;
- import cn.cge.track.service.TrackService;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.connection.Message;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
- import org.springframework.data.redis.listener.RedisMessageListenerContainer;
- import org.springframework.stereotype.Component;
- import org.springframework.web.client.RestTemplate;
-
- @Component
- public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
- private final static Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);
-
- public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
- super(listenerContainer);
- }
-
- @Autowired
- private RedisTemplate redisTemplate;
-
- @Autowired
- private TrackService trackService;
-
- @Override
- public void onMessage(Message message, byte[] pattern) {
- try {
- String expiredKey = message.toString();//获取所有key
- //以下是你想执行的代码逻辑
- if(expiredKey.endsWith("_upload!!!")){
- System.out.print("我想输出这句话")
- }
- }catch (Exception e){
- e.printStackTrace();
- }
-
- }
- }
- package cn.cge.main.config;
-
- /**
- * 这一段直接复制,写死的
- **/
- 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;
-
- @Configuration
- public class RedisListenerConfig {
- @Bean
- RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
-
- RedisMessageListenerContainer container = new RedisMessageListenerContainer();
- container.setConnectionFactory(connectionFactory);
- return container;
- }
- }
下面是自己写的代码:
- String uploadKey = "这是自定义的key_upload!!!";
- //插入缓存
- redisTemplate.opsForValue().set(uploadKey,"这是值!");
- //设置缓存过期时间为10秒
- redisTemplate。expire(uploadkey,10,TimeUnit.SECOUNDS);
-
- //当缓存过期,就会自动执行第一段代码块中的逻辑代码,因为key结尾是_upload!!!,其他的不影响!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。