使用Spring KeyGenerator生成唯一的缓存键不起作用 [英] Generating unique cache key with Spring KeyGenerator not working
问题描述
当我的缓存键在Spring中使用 @Cacheable
注释发生冲突时,我遇到了问题。例如,使用以下两种方法:
I'm having the issue when my cache keys are colliding in Spring using the @Cacheable
annotation. For instance, with the following two methods:
@Cacheable("doOneThing")
public void doOneThing(String name) {
// do something with name
}
@Cacheable("doAnotherThing")
public void doAnotherThing(String name) {
// do some other thing with name
}
这是我的缓存配置,其中我'我添加了一个 keyGenerator
和一个 cacheManager
bean:
Here is my cache configuration, in which I've added a keyGenerator
and a cacheManager
bean:
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public JedisConnectionFactory redisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
redisTemplate.setConnectionFactory(cf);
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append(method.getName());
for (Object param : params) {
sb.append(param.toString());
}
return sb.toString();
}
};
}
}
出于某种原因,缓存键始终设置为方法中的 name
参数,而不是 keyGenerator.generate(..)
方法的结果,导致两种方法返回相同的缓存结果。
For some reason, the cache key always gets set to the name
parameter in the method, not the result of the keyGenerator.generate(..)
method, causing both methods to return the same cache result.
我知道我可以在每个 @Cacheable
注释上手动指定密钥,但对于我想要缓存的每种方法,这似乎都有点广泛。
I know that I can specify the key manually on each @Cacheable
annotation, but that seems a little extensive for every method I'd like to cache.
我是注意到将 @Cacheable
注释中的 keyGenerator
选项设置为我的bean的名称可以解决问题,就像这样:
I've noticed that setting the keyGenerator
option inside of the @Cacheable
annotation to the name of my bean resolves the issue, like so:
@Cacheable(value = "doOneThing", keyGenerator = "keyGenerator")
public void doOneThing(String name) {
// do something with name
}
并设置<该类的 @CacheConfig
注释中的code> keyGenerator 选项也解决了该问题。看来这不应该是必要的。我错过了什么吗?
And setting the keyGenerator
option in the @CacheConfig
annotation on the class also resolves the issue. It seems that this shouldn't be necessary though. Am I missing something?
推荐答案
您的配置应该实现 CachingConfigurer
(通常是你)将从 CachingConfigurerSupport
扩展,以自定义缓存的工作方式。
Your configuration should implement CachingConfigurer
(usually you would extend from CachingConfigurerSupport
) to customize how caching works.
这篇关于使用Spring KeyGenerator生成唯一的缓存键不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!