Springcahce統合redis設定の有効期限

8552 ワード

前にspringboot統合springcahceを試してみました.https://www.cnblogs.com/a565810497/p/10931426.html
guavaでspringcahceの有効時間を設定してみました.https://www.cnblogs.com/a565810497/p/10932149.html
しかし結局はあまり柔軟ではないと思います.guava設定が有効な時間はデフォルトを設定するだけで、複数を設定することはできません.springcahceはデータベースにキャッシュされていないので、redisはspringcahceと集合するのに適しています.
まずspringcahce統合redisを使用します.まず、記事を参照してください.https://blog.battcn.com/2018/05/13/springboot/v2-cache-redis/
依存の追加
porm.xml redisの依存性の追加

    org.springframework.boot
    spring-boot-starter-data-redis


    org.apache.commons
    commons-pool2


    org.springframework.boot
    spring-boot-starter-test
    test

属性の構成
## Redis     
spring.redis.host=127.0.0.1
## Redis       
spring.redis.port=6379
## Redis       (    )
spring.redis.password=
#           ,Spring Cache            
spring.cache.type=redis
#       (  )
spring.redis.timeout=10000
# Redis      16   ,           
spring.redis.database=0
#         (          )    8
spring.redis.lettuce.pool.max-active=8
#            (          )    -1
spring.redis.lettuce.pool.max-wait=-1
#                8
spring.redis.lettuce.pool.max-idle=8
#                0
spring.redis.lettuce.pool.min-idle=0

次に、redisに基づいてspringcacheの有効時間を設定できます.https://blog.csdn.net/weixin_42047790/article/details/84189275
起動クラス構成が有効な時間:
@Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                this.getRedisCacheConfigurationWithTtl(30*60), //     ,     key      
                this.getRedisCacheConfigurationMap() //    key   
        );
    }

    private Map getRedisCacheConfigurationMap() {
        Map redisCacheConfigurationMap = new HashMap<>();
        //DayCache SecondsCache        
        redisCacheConfigurationMap.put("DayCache", this.getRedisCacheConfigurationWithTtl(24*60*60));
        redisCacheConfigurationMap.put("SecondsCache", this.getRedisCacheConfigurationWithTtl(2));
        return redisCacheConfigurationMap;
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));

        return redisCacheConfiguration;
    }

    @Bean
    public KeyGenerator wiselyKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append("." + method.getName());
                if(params==null||params.length==0||params[0]==null){
                    return null;
                }
                String join = String.join("&", Arrays.stream(params).map(Object::toString).collect(Collectors.toList()));
                String format = String.format("%s{%s}", sb.toString(), join);
                //log.info("  key:" + format);
                return format;
            }
        };
    }

異なる時間のcacheをそれぞれ使用します.
@Override
    @Cacheable(value = "SecondsCache")
    public TestTime getTestTime(){
        return new TestTime(new Date());
    }

    @Override
    @Cacheable(value = "DayCache")
    public TestTime getTestTime1(){
        return new TestTime(new Date());
    }

Secondscacheは2秒のライフサイクルを設定しています.
DayCacheは1日のライフサイクルを設定しています.
なぜそんなに煩雑な設定なのか、実はredisはキャッシュを追加するときに有効時間を設定することができますが、私たちは注釈の方式@cacheableでコード侵入を必要とせずに注釈を実現したいので、redisとspringcahceを結合します.
 
本明細書のソース:https://gitee.com/Hiro-D/Java/tree/master/springcache-redis