使用Spring Cache实现多个缓存实现

前端之家收集整理的这篇文章主要介绍了使用Spring Cache实现多个缓存实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在开发一个Spring Boot应用程序,我需要使用分布式(例如Hazelcast)和本地(例如Guava)缓存.有没有办法配置Spring Cache在使用@Cacheable时使用它们并根据缓存名称决定需要哪个实现?

我尝试为HZ和Guava创建一个配置来定义里面的缓存名称,但是Spring抱怨它无法找到应该由HZ处理的缓存名称.当我独家使用HZ或Guava时,它们起作用.

最佳答案

Which implementation is needed based on the cache name?

不是基于缓存名称,而是基于CacheManager可能,请将其中一个声明为Primary CacheManager,如下所示:

  1. @Configuration
  2. @EnableCaching
  3. @PropertySource(value = { "classpath:/cache.properties" })
  4. public class CacheConfig {
  5. @Bean
  6. @Primary
  7. public CacheManager hazelcastCacheManager() {
  8. ClientConfig config = new ClientConfig();
  9. HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
  10. return new HazelcastCacheManager(client);
  11. }
  12. @Bean
  13. public CacheManager guavaCacheManager() {
  14. GuavaCacheManager cacheManager = new GuavaCacheManager("mycache");
  15. CacheBuilder

并在课程级别指定为:

  1. @Service
  2. @CacheConfig(cacheManager="hazelcastCacheManager")
  3. public class EmployeeServiceImpl implements IEmployeeService {
  4. }

或者在方法级别:

  1. @Service
  2. public class EmployeeServiceImpl implements IEmployeeService {
  3. @Override
  4. @Cacheable(value = "EMPLOYEE_",key = "#id",cacheManager= "guavaCacheManager")
  5. public Employee getEmployee(int id) {
  6. return new Employee(id,"A");
  7. }
  8. }

如果您必须坚持使用Cache名称,那么您可以使用多个CacheManager.

猜你在找的Spring相关文章