[英]What is the difference between CacheResolver and KeyGenerator and when to use each one of them
I am adding a caching mechanism to my web application. 我正在向我的Web应用程序添加缓存机制。 After doing a research I decided to use
Ehcache
with Spring. 经过研究后,我决定将
Ehcache
与Spring一起使用。
Adding @Cachable
annotation to a method will execute the method once and for any further invocations the response will be returned from the cache. 在方法中添加
@Cachable
批注将执行一次该方法,并且对于任何进一步的调用,将从缓存中返回响应。
The problem is that I need to decide at runtime (let's suppose according to the logged in user) which cache I want to use. 问题是我需要在运行时决定(我想根据登录的用户)要使用哪个缓存。
I have come to a point where I need to decide whether to use KeyGenerators
or cacheResolver
. 我已经到了需要决定是否使用
KeyGenerators
或cacheResolver
。
I searched for best practices, when to use each one of them but did not find any good readings. 我搜索了最佳实践,何时使用它们中的每一种,但没有发现任何好的阅读材料。 I hope If anybody can clarify the differences and elaborate on best practices and to do's and not to do's.
我希望任何人都可以澄清差异,并详细说明最佳做法以及要做的事情和不要做的事情。
KeyGenerator: 的KeyGenerator:
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, String loggedInUserId) {
StringBuilder sb = new StringBuilder();
sb.append("cache_");
sb.append(loggedInUserId);
return sb;
}
};
CacheResolver CacheResolver
class loggedInUserCacheResolver implements CacheResolver {
@Override
public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
Collection<Cache> caches = new ArrayList<>();
// do some logic and return caches to use.
return caches;
}
}
The KeyGenerator
will only allow you to manipulate the creation of the cache key. KeyGenerator
仅允许您操纵缓存密钥的创建。 However all keys will still belong to a single cache, even though they will not have any collision. 但是,即使它们没有任何冲突, 所有键仍将属于一个缓存。
The CacheResolver
allow you to use logic to pick which Cache
to use. CacheResolver
允许您使用逻辑来选择要使用的Cache
。
Given your initial statement, you would need a CacheResolver
for your use case. 给定您的初始声明,您将需要用例一个
CacheResolver
。 Note that I did not double check if the cache is resolved once or for each invocation. 请注意,我没有仔细检查缓存是一次还是每次调用解析。
Note that you could combine both annotations to have a custom cache and a custom key definition. 请注意,您可以将两个注释组合在一起以具有自定义缓存和自定义键定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.