1. Overview
1.概述
In this quick tutorial, we’re going to illustrate how to create a custom key generator with Spring Cache.
在这个快速教程中,我们将说明如何用Spring Cache创建一个自定义密钥生成器。
For an introduction to the above module, please refer to this article.
关于上述模块的介绍,请参考到这篇文章。
2. KeyGenerator
2、密钥生成器
This is responsible for generating every key for each data item in the cache, which would be used to lookup the data item on retrieval.
它负责为缓存中的每个数据项生成每一个密钥,在检索时用于查询该数据项。
The default implementation here is the SimpleKeyGenerator – which uses the method parameters provided to generate a key. This means that if we have two methods that use the same cache name and set of parameter types, then there’s a high probability that it will result in a collision.
这里的默认实现是SimpleKeyGenerator – ,它使用提供的方法参数来生成一个密钥。这意味着,如果我们有两个方法使用相同的缓存名称和一组参数类型,那么很有可能会导致碰撞的发生。
It also implies that the cache data can be overwritten by another method.
这也意味着缓存数据可以被其他方法覆盖。
3. Custom KeyGenerator
3.自定义密钥生成器
A KeyGeneratorneeds to implement just one single method:
一个KeyGenerator只需要实现一个单一的方法。
Object generate(Object object, Method method, Object... params)
If it isn’t implemented or used correctly, it can lead to overwriting cache data.
如果没有正确实现或使用,可能会导致覆盖缓存数据。
Let’s look at the implementation:
让我们来看看实施情况。
public class CustomKeyGenerator implements KeyGenerator {
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getSimpleName() + "_"
+ method.getName() + "_"
+ StringUtils.arrayToDelimitedString(params, "_");
}
}
After that, we have two possible ways of using it; the first is declaring a bean in the ApplicationConfig.
之后,我们有两种可能的使用方式;第一种是在ApplicationConfig中声明一个bean。
It’s important to remark that the class has to extend from CachingConfigurerSupport or implement CacheConfigurer:
值得注意的是,该类必须从CachingConfigurerSupport延伸或实现CacheConfigurer。
@EnableCaching
@Configuration
public class ApplicationConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
Cache booksCache = new ConcurrentMapCache("books");
cacheManager.setCaches(Arrays.asList(booksCache));
return cacheManager;
}
@Bean("customKeyGenerator")
public KeyGenerator keyGenerator() {
return new CustomKeyGenerator();
}
}
The second way is using it just for a particular method:
第二种方式是只为某个特定的方法而使用它。
@Component
public class BookService {
@Cacheable(value = "books", keyGenerator = "customKeyGenerator")
public List<Book> getBooks() {
List<Book> books = new ArrayList<>();
books.add(new Book("The Counterfeiters", "André Gide"));
books.add(new Book("Peer Gynt and Hedda Gabler", "Henrik Ibsen"));
return books;
}
}
4. Conclusion
4.总结
In this article, we’ve explored a way of implementing a custom Spring Cache’s KeyGenerator.
在这篇文章中,我们探索了一种实现自定义Spring Cache的KeyGenerator的方法。
As always, the full source code of the examples is available over on GitHub.
一如既往,这些示例的完整源代码可在GitHub上获得over。