spring的redis注解缓冲设置有效时间@Cacheable、@Cacheput

概述

  cache的缓冲注解并没有专门的属性来设置缓冲的有效时间,那么使用什么样的方法来设置缓冲注解的有效时间呢?我个人这边有2种方式。

1、不灵活方式设置

  我们在配置cacheManger的时候里面都会配置redis的连接,这样我们就可以直接在redis配置上设置好缓冲数据的有效时间,这种方式设置出来的有效时间,所有的数据的有效时间都是一样的而且无法进行灵活的修改。一般不采用。

2、灵活的方式设置有效时间

  spring配置cache注解的时候我们一般都采用对的是RedisCacheManager,在new对象的时候里面可以设置RedisCacheConfiguration,通过这个以及注解里面的value就可以设置不同注解的有效时间。

package org.loulan.dawn.application.common.config.cache;

import lombok.extern.slf4j.Slf4j;
import org.loulan.dawn.application.common.pojo.exception.ConfigurationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/*********************************************************
 ** Description: 缓冲注解配置
 ** <br><br>
 ** Date: Created in 2019/7/4  11:41
 ** @author 楼兰
 ** @version 0.0.0
 *********************************************************/
@Slf4j
public class CacheConfiguration {

    /**
     * Description :安全管理部分配置的缓冲管理器
     * @param
     * @return
     * @exception
     * @author     :loulan
     * */
    @Bean
    @Primary
    public CacheManager cacheManager(
           @Autowired RedisConnectionFactory redisConnectionFactory
    ) {
        log.info("进入cacheManager配置");
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        //初始化RedisCacheManager
        return new RedisCacheManager(
                redisCacheWriter,
                this.getRedisCacheConfigurationWithTtl(0), //默认策略,没有配置过的value(cacheName)就会使用这个时间策略
                this.getRedisCacheConfigurationMap());             //指定value 策略
    }

    /**
     * Description : 指定value策略,只要注解的value(cacheName)设置的是这里面的值,就会使用这种测率
     * 个人认为这里是spring redis的一种缓冲缺陷,可以使用缓冲连接rendis但是却无法设置缓冲数据的有效时间,所以采用这种策略的方式
     * @param
     * @return      指定value的策略集合
     * @exception
     * @author     :loulan
     * */
    private Map<String,RedisCacheConfiguration> getRedisCacheConfigurationMap () {
        Map<String, RedisCacheConfiguration> map = new HashMap<>();
        
        
        // 有效时间1分钟
        map.put("m1",this.getRedisCacheConfigurationWithTtl(1 * 60));
        
        // 有效时间30分钟
        map.put("m30",this.getRedisCacheConfigurationWithTtl(30 * 60))

        return map;
    }

    /**
     * Description :设置Redis缓冲配置以及配置redis有效时间
     * @param       seconds 数据有效时间
     * @return
     * @exception
     * @author     :loulan
     * */
    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        //设置CacheManager的值序列化方式为json序列化
        RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                .fromSerializer(jsonSerializer);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(pair)   //设置redis的序列话方式
                .entryTtl(Duration.ofSeconds(seconds))
                .disableKeyPrefix()          //禁止该缓冲使用redis前缀
                .disableCachingNullValues(); //禁止对null值进行缓冲
        return redisCacheConfiguration;
    }
}

  如上,如果注解的value设置为m1,那么当前注解缓冲数据的有效时间就是1分钟。如果value设置为m30,那么当前注解缓冲数据的有效时间就是30分钟。如果设置的不是m1也不是m30(当前程序里面就设置了m1和m30),那么就会启用默认策略,有效时间为永久有效。

    @Cacheable(value = "m30",
            key = "T(org.loulan.dawn.application.common.pojo.config.redis.RedisArea).USER_INFO + #id",
            unless = "#result == null")

注解得使用

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架通过Spring Cache提供了一套强大的缓存体系,可以轻松地实现缓存数据,提高应用程序的性能。Spring框架提供了三个主要的注解来实现缓存:@Cacheable、@CachePut和@CacheEvict。 @Cacheable注解用于将方法的结果缓存起来,以便在下次请求时,如果参数相同,则可以直接从缓存获取结果,而不需要重新计算。该注解适用于如果计算结果比较耗时,或者需要从数据库或其他外部资源提取数据的情况。 @CachePut注解用于更新缓存的数据。它与@Cacheable注解类似,但不同的是,它总是更新缓存数据,而不管缓存是否已经存在该key的值。所以,可以使用这个注解来更新缓存的数据。 @CacheEvict注解用于从缓存删除数据。它在需要删除缓存数据的情况下使用。它可以删除指定的key对应的缓存,也可以清空所有缓存数据。 这三个注解都有一个可选参数Named:如果指定了该参数,则缓存将使用指定的名称使用。如果未指定,则使用默认的名称。可以使用不同名称的缓存来存储不同类型的数据,并使用不同的缓存策略来控制它们的存储方式。 除了Spring自带的缓存提供者之外,还可以使用其他的缓存提供者,如EhcacheRedis、Memcached等等。在使用缓存时,需要注意的是,不同的缓存提供者之间可能会有不同的限制和性能差异。因此,必须根据实际情况选择最适合的缓存提供者和缓存策略,以获取最好的性能和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值