How can I prefix cacheNames with spring.cache.redis.key-prefix?

限于喜欢 提交于 2021-01-29 11:00:47

问题


I managed to make the cacheNames work and my Redis keys look like this.

{cacheName}::{myKey}
{cacheName}::{myKey}

Now I wonder how can I prefix the {cacheName} part with my configured value of spring.cache.redis.key-prefix?

When I put these entries,

spring.cache.redis.key-prefix=some::
spring.cache.redis.use-key-prefix=true

I want the keys look like this.

some::{cacheName}::{myKey}
some::{cacheName}::{myKey}

回答1:


I'm not sure of the way of using configuration along with internal functionalities.

I piled an issue. https://jira.spring.io/browse/DATAREDIS-1006

I managed to achieve what I wanted to do with following codes.

@PostConstruct
private void onPostConstruct() {
    if (springCacheRedisKeyPrefix != null) {
        springCacheRedisKeyPrefix = springCacheRedisKeyPrefix.trim();
    }
    if (springCacheRedisUseKeyPrefix && springCacheRedisKeyPrefix != null
        && !springCacheRedisKeyPrefix.isEmpty()) {
        cacheKeyPrefix = cacheName -> springCacheRedisKeyPrefix + "::" + cacheName + "::";
    } else {
        cacheKeyPrefix = CacheKeyPrefix.simple();
    }
}

@Bean
public RedisCacheManager cacheManager(final RedisConnectionFactory connectionFactory) {
    final RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
            .cacheDefaults(defaultCacheConfig()
                                   .computePrefixWith(cacheKeyPrefix)
                                   .entryTtl(Duration.ofMillis(springCacheRedisTimeToLive))
            )
            .build();
    return cacheManager;
}

@Value(value = "${spring.cache.redis.key-prefix:}")
private String springCacheRedisKeyPrefix;

@Value("${spring.cache.redis.use-key-prefix:false}")
private boolean springCacheRedisUseKeyPrefix;

@Value("${spring.cache.redis.time-to-live:1200000}")
private long springCacheRedisTimeToLive;

private transient CacheKeyPrefix cacheKeyPrefix;


来源:https://stackoverflow.com/questions/56764225/how-can-i-prefix-cachenames-with-spring-cache-redis-key-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!