1. 概述
在本快速教程中,我們將演示如何使用 Spring Cache 創建自定義密鑰生成器。
對於上述模塊的介紹,請參閲這篇文章。
2. KeyGenerator
該組件負責為緩存中的每個數據項生成所有鍵,這些鍵將在檢索數據時用於查找數據項。
默認實現是 SimpleKeyGenerator,它使用提供的參數方法來生成鍵。這意味着如果兩個方法使用相同的緩存名稱和參數類型,則很可能導致衝突。
這還意味着緩存數據可以被另一個方法覆蓋。
3. 自定義 KeyGenerator
一個 KeyGenerator 需要實現一個單一的方法:
Object generate(Object object, Method method, Object... params)如果未正確實施或使用,可能會導致緩存數據被覆蓋。
讓我們來看一下實現方式:
public class CustomKeyGenerator implements KeyGenerator {
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getSimpleName() + "_"
+ method.getName() + "_"
+ StringUtils.arrayToDelimitedString(params, "_");
}
}之後,我們有以下兩種使用方法:第一種是在 ApplicationConfig 中聲明一個 Bean。
需要注意的是,該類必須從 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();
}
}另一種方法是僅將其用於特定方法:
@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. 結論
在本文中,我們探討了一種實現自定義 Spring Cache 的 KeyGenerator 的方法。