SpringBoot @Cacheable Redis 设置缓存过期时间

1.x 设置 

@Bean
@Primary
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);

    Map<String, Long> expires = new HashMap<>();

    expires.put("timeout", 60L);

    // 设置超时
// 根据特定名称设置有效时间
    redisCacheManager.setExpires(expires);

    // 设置默认的时间
    redisCacheManager.setDefaultExpiration(cacheDefaultExpiration);

    return redisCacheManager;

}

使用方式:

转载:传送门


@Configuration
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600 * 12)//最大过期时间
@EnableCaching
public class RedisConfig {
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        Map<String, Long> expires = new HashMap<>();
        expires.put("12h", 3600 * 12L);
        expires.put("1h", 3600 * 1L);
        expires.put("10m", 60 * 10L);
        rcm.setExpires(expires);
//        rcm.setDefaultExpiration(60 * 60 * 12);//默认过期时间
        return rcm;
    }
}


//----------------------------------------------------------

@Cacheable(value = "12h", key = "#root.methodName")
 @Override
   public List<User> getUserArticleRank() {
       //获得排行榜前10名的用户,每12小时刷新一次
       return userRepository.findTop10ByArticleSize();
   }

2.x 设置

转载:传送门

  /**
     * 2.XX版本的配置
     *
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();  // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
        config = config.entryTtl(Duration.ofMinutes(2))     // 设置缓存的默认过期时间,也是使用Duration设置
                .disableCachingNullValues();     // 不缓存空值

        // 设置一个初始化的缓存空间set集合
        Set<String> cacheNames = new HashSet<>();
        cacheNames.add("catalog_test_id");
        cacheNames.add("catalog_test_name");

        // 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("catalog_test_id", config);
        configMap.put("catalog_test_name", config.entryTtl(Duration.ofMinutes(5)));

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)     // 使用自定义的缓存配置初始化一个cacheManager
                .initialCacheNames(cacheNames)  // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }
@CacheConfig(cacheNames = "catalog_test_name")
public class SsoCache{
	@Cacheable(keyGenerator = "wiselyKeyGenerator")
	public String getTokenByGsid(String gsid) 
}

-------------------------------------
自定义Redis Cache 自动化配置替换系统默认的cacheManager
 * 扩展cache name 支持 # 号分隔 cache name 和 超时 ttl(单位秒)。

<p>
 * 示例:@CachePut(value = "user#300", key = "#id")
 * </p>

参考:https://gitee.com/brucewuu/spring-ultron/blob/master/spring-ultron-projects/ultron-redis/src/main/java/org/springultron/redis/config/RedisCacheAutoConfiguration.java

---------------------------------------------------------
使用(name中增加“#”,后面是过期时间,不加则走默认时间)

 @Cacheable(cacheNames = "catalog_test_name#120", unless = "#result==null")
    public UserEntity findUserByUserName(String userName) {
        return userRepository.findUserByUserName(userName);
    }

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
@Cacheable注解是Spring框架用于缓存方法返回结果的注解。当一个方法被@Cacheable注解标记后,Spring会检查缓存是否存在该方法的返回值,如果存在,则直接从缓存获取结果并返回;如果不存在,则执行方法体,并将返回值存入缓存。 使用@Cacheable注解需要注意以下几点: 1. 在需要缓存结果的方法上使用@Cacheable注解。 2. 可以指定缓存的名称,通过value属性来指定,如:@Cacheable(value="myCache")。 3. 可以指定缓存的Key,通过key属性来指定,如:@Cacheable(key="#param")。其#param表示方法的参数值,还可以使用SpEL表达式来动态构建key。 4. 默认情况下,缓存的Key是由方法的所有参数组成的,如果不希望使用所有参数构建Key,可以使用condition属性来限制条件,如:@Cacheable(condition="#param.length() < 10")。这里的condition表示只有当参数长度小于10时才进行缓存。 5. 可以指定缓存过期时间,通过设置expire属性来指定,如:@Cacheable(expire=3600)。单位为秒,默认为-1,表示永不过期。 示例代码: ```java @Service public class UserService { @Cacheable(value = "users", key = "#id") public User getUserById(String id) { // 从数据库获取用户信息 // ... return user; } } ``` 上述示例,getUserById方法会根据id参数从缓存获取User对象,如果缓存不存在,则执行方法体并将返回值存入缓存。 需要注意的是,@Cacheable注解只能用于Spring容器管理的Bean,即被@Service、@Component等注解标记的类的方法才能被缓存。另外,为了使@Cacheable注解生效,需要在Spring配置文件配置缓存管理器(如使用EhcacheRedis等)。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值