问题描述
我想为我的 RedisCacheManager 使用 xml 配置的应用程序设置自定义缓存键前缀,我的目标是,如果缓存键是 student-detail,则缓存键应该是 test :: student-detail 或 prod :: student-detail,我已经将usePrefix 设置为true,但是我找不到定义实际键值的方法。下面是我的 cacheManager 配置的摘录。
elasticsearch.helpers.errors.BulkIndexError:
('18 document(s) Failed to index.',[{'index': {'_index': 'movie_data','_type': '_doc','_id':
'KmwJwncBEtJeL_lPLqQ8','status': 400,'error': {'type': 'mapper_parsing_exception','reason':
'Failed to parse','caused_by': {'type': 'not_x_content_exception','reason': 'Compressor detection
can only be called on some xcontent bytes or compressed xcontent bytes'
有关信息,我知道在 Spring Boot 中就像在应用程序属性中设置一个属性一样简单:
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
c:redisOperations-ref="redistemplate"
c:defaultExpiration=3600
c:usePrefix="true">
</bean>
只是为了说明为什么我为非 Spring Boot Java 应用程序精确定位。
解决方法
解决方案是通过实现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 的属性文件条目中获取。 如果 prefixString 值是 testing 并且 cacheName 是 student-details-cache 那么你的缓存键将带有前缀: testing:student-details-cache::