SpringBoot配置Redis自定义过期时间

Redis配置依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-redis</artifactId>
        <version>1.4.4.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.8.1.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.0</version>
</dependency>

SpringBoot-Reids配置文件

package com.regs.tms.common.redis;

@Configuration
@EnableCaching// 启用缓存,这个注解很重要
@ConfigurationProperties(prefix = "spring.redis")
@Data
public class RedisCacheConfig extends CachingConfigurerSupport {
	private String host;
	private Integer port;
	private Integer database;
	private String password;

	@Bean("redisTemplate")
	public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
	    StringRedisTemplate template = new StringRedisTemplate();
	    template.setConnectionFactory(factory);
	    //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
	    Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
	    ObjectMapper mapper = new ObjectMapper();
	    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
	    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
	    serializer.setObjectMapper(mapper);
	    template.setValueSerializer(serializer);
	    template.setHashValueSerializer(serializer);
	    // 设置键(key)的序列化采用StringRedisSerializer。
	    template.setKeySerializer(new StringRedisSerializer());
	    template.setHashKeySerializer(new StringRedisSerializer());
	    //打开事务支持
	    template.setEnableTransactionSupport(true);
	    template.afterPropertiesSet();
	    return template;
	}

	@Bean
	public PlatformTransactionManager transactionManager(DataSource dataSource) throws SQLException {
	    //配置事务管理器
	    return new DataSourceTransactionManager(dataSource);
	}

	@Bean("stringRedisTemplate")
	public StringRedisTemplate stringRedisTemplate() {
	    Integer port = this.port == null ? 6379 : this.port;
	    JedisConnectionFactory jedis = new JedisConnectionFactory();
	    jedis.setHostName(host);
	    jedis.setPort(port);
	    if (StringUtils.isNotEmpty(password)) {
	        jedis.setPassword(password);
	    }
	    if (database != null) {
	        jedis.setDatabase(database);
	    } else {
	        jedis.setDatabase(0);
	    }
	    // 初始化连接pool
	    jedis.afterPropertiesSet();
	    // 获取连接template
	    StringRedisTemplate temple = new StringRedisTemplate();
	    temple.setConnectionFactory(jedis);
	    return temple;
	}
}

自定义失效注解

package com.regs.tms.common.redis.annotation;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface CacheDuration {
    //Sets the expire time (in seconds).
    public long duration() default 60;
}

自定义失效配置

package com.regs.tms.common.redis.annotation;

 /**
 * ExpireCacheManager,继承自RedisCacheManager,
 * 用于对@CacheExpire解析及有效期的设置
 */
public class RedisExpireCacheManager extends RedisCacheManager implements ApplicationContextAware, InitializingBean {
    private ApplicationContext applicationContext;

    public RedisExpireCacheManager(RedisTemplate redisTemplate) {
        super(redisTemplate);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        parseCacheExpire(applicationContext);
    }

    private void parseCacheExpire(ApplicationContext applicationContext) {
        final Map<String, Long> cacheExpires = new HashMap<>(16);
        //扫描有注解
        String[] beanNames = applicationContext.getBeanNamesForAnnotation(Cacheable.class);
        for (String beanName : beanNames) {
            final Class clazz = applicationContext.getType(beanName);
            addCacheExpires(clazz, cacheExpires);
        }
        //设置有效期
        super.setExpires(cacheExpires);
    }

    private void addCacheExpires(final Class clazz, final Map<String, Long> cacheExpires) {
        ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                ReflectionUtils.makeAccessible(method);
                //根据CacheExpire注解获取时间
                CacheExpire cacheExpire = findCacheExpire(clazz, method);
                if (cacheExpire != null) {
                    Cacheable cacheable = findAnnotation(method, Cacheable.class);
                    String[] cacheNames = isEmpty(cacheable.value()) ? new String[]{} : cacheable.value();
                    for (String cacheName : cacheNames) {
                        cacheExpires.put(cacheName, cacheExpire.expire());
                    }
                }
            }
        }, new ReflectionUtils.MethodFilter() {
            @Override
            public boolean matches(Method method) {
                return null != findAnnotation(method, Cacheable.class);
            }
        });
    }

    /**
     * CacheExpire标注的有效期,优先使用方法上标注的有效期
     *
     * @param clazz
     * @param method
     * @return
     */
    private CacheExpire findCacheExpire(Class clazz, Method method) {
        CacheExpire methodCache = findAnnotation(method, CacheExpire.class);
        if (null != methodCache) {
            return methodCache;
        }
        CacheExpire classCache = findAnnotation(clazz, CacheExpire.class);
        if (null != classCache) {
            return classCache;
        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值