Reputation: 133
I would like to set a custom cache key prefix for my application which uses xml configuration for my RedisCacheManager, my goal is, if the cache key is student-detail, the cache key should be test :: student-detail or prod :: student-detail, I have already set usePrefix to true, but I cant find a way to define the actual key value. Here below an extract of my cacheManager configuration.
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
c:redisOperations-ref="redisTemplate"
c:defaultExpiration=3600
c:usePrefix="true">
</bean>
For the information, I know in spring boot is as simple as setting a property in the application properties as :
spring.cache.redis.key-prefix=some::
spring.cache.redis.use-key-prefix=true
Just to put some context why I precised for non spring boot java application.
Upvotes: 0
Views: 3609
Reputation: 133
The solution is to create your custom redis cache prefix by implementing RedisCachePrefix.See the code below
package com.cache.custom.utils;
import com.morgan.design.properties.ReloadableProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCachePrefix;
import org.springframework.data.redis.serializer.StringRedisSerializer;
public class MyRedisCachePrefix implements RedisCachePrefix {
/** The Prefix */
@ReloadableProperty("prefixString")
private String personalPrefixString;
/** The key string redis serializer */
@Autowired
String StringRedisSerializer stringRedisSerializer;
/** The delimiter */
private final String delimiter = "::";
@Override
public byte[] prefix(String cacheName) {
return stringRedisSerializer.serialize(personalPrefixString.concat(":").concat(cacheName).concat(this.delimiter));
}
}
Then on the xml :
<bean id=stringRedisSerializer"
class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<bean id="redisCachePrefix"
class="com.cache.custom.utils.MyRedisCachePrefix"/>
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
c:redisOperations-ref="redisTemplate"
p:defaultExpiration=3600
p:usePrefix="true"
p:cachePrefix-ref="redisCachePrefix"
>
</bean>
N.B : personalPrefixString value will be taken from properties files entry of prefixString. If prefixString value is testing and cacheName is student-details-cache then your cache key will be prefixed by : testing:student-details-cache::
Upvotes: 0