我正在使用spring boot+redis将数据存储在缓存中。
我的控制器具有以下配置:
public class CacheController {
@GetMapping("/{key}")
@Cacheable(value = "myCacheValue", keyGenerator = "customKeyGenerator")
public String getByKey(@PathVariable("key") String key) {
return key + System.currentTimeMillis();
}
}
我的自定义密钥生成器是:
public class CustomKeyGenerator implements KeyGenerator {
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getSimpleName())
.append("-")
.append(method.getName());
if (params != null) {
for (Object param : params) {
sb.append("-")
.append(param.getClass().getSimpleName())
.append(":").append(param);
}
}
return sb.toString();
}
}
当我在Redis中连接时,我有这个密钥:
1 - redis-cli --raw
KEYS *
myCacheValue~keys
��t$CacheController-getByKey-String:key9
2 - redis-cli
KEYS *
myCacheValue~keys
\xac\xed\x00\x05t\x00$CacheController-getByKey-String:key9
为什么这些字符出现在“cachecontroller”之前?
注意:我的密钥生成器以我的类名开头。
我只希望我的密钥名是这样的:
cachecontroller getbykey字符串:mykey
最佳答案
从doc中,您可以使用RedisCacheConfiguration
bean自定义您的redisCacheManager
:
@Configuration
public class CacheConfiguration {
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig();
}
}
默认配置为:
public static RedisCacheConfiguration defaultCacheConfig() {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
registerDefaultConverters(conversionService);
return new RedisCacheConfiguration(Duration.ZERO, true, true, CacheKeyPrefix.simple(),
SerializationPair.fromSerializer(new StringRedisSerializer()),// this will use string as the key serializer
SerializationPair.fromSerializer(new JdkSerializationRedisSerializer()), conversionService);
}
关于spring-boot - Spring boot + Redis - 生成一个奇怪的 key ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51291548/