解决方案是通过实现 RedisCachePrefix 来创建您的自定义 redis 缓存前缀。请参见下面的代码
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));
}
}
然后在 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>
注意:personalPrefixString 值将从前缀字符串的属性文件条目中获取。如果 prefixString 值是 testing 并且 cacheName 是 student-details-cache 那么你的缓存键将以 : testing:student-details-cache:: 为前缀