Spring Boot 2.2.6 Redis 自定义缓存过期时间

1. 自定义CacheManager 继承RedisCacheManager

package com.xingte.hmiserver.cache.redis;

import com.xingte.hmiserver.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.internal.StringUtil;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;

@Slf4j
public class MyRedisCacheManager extends RedisCacheManager {

    public MyRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        if (!StringUtils.isEmpty(name) && name.contains("#")) {
            String numStr = name.split("#")[1];
            if (StringUtil.isNumeric(numStr)) {
                //默认单位为秒,可根据需求拓展
                return super.createRedisCache(name, cacheConfig.entryTtl(Duration.ofSeconds(Integer.parseInt(numStr))));
            }
        }
        //不包含则走默认时间
        return super.createRedisCache(name, cacheConfig);
    }
}

2. 配置CacheManager,返回自定义RedisCacheManager

@Slf4j
@Configuration
public class RedisCacheConfig {

    private final RedisConnectionFactory redisConnectionFactory;


    @Autowired
    public RedisCacheConfig(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }
    
    @Bean
    public CacheManager cacheManager() {
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        RedisCacheConfiguration conf = RedisCacheConfiguration.defaultCacheConfig()
                //默认缓存过期时间5分钟
                .entryTtl(Duration.ofSeconds(60*5))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer));
        return new MyRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), conf);
    }
    }

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

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

参考:Spring Boot 使用Redis作为默认缓存,且注解支持配置过期时间

你可能感兴趣的:(springboot,web)