Jin Kwon
Jin Kwon

Reputation: 21997

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

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}

Upvotes: 1

Views: 14197

Answers (1)

Jin Kwon
Jin Kwon

Reputation: 21997

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;

Upvotes: 4

Related Questions