我正在开发Spring Boot需要同时使用分布式(例如Hazelcast)和本地(例如Guava)缓存的应用程序。有没有一种方法可以配置Spring Cache在使用时同时使用@Cacheable并根据缓存名称决定需要哪种实现?
Spring Boot
Hazelcast
Guava
@Cacheable
我尝试为HZ和Guava创建一个配置,在其中定义缓存名称,但是Spring抱怨它找不到应该由HZ处理的缓存名称。当我仅使用HZ或番石榴时,它们会起作用。
根据缓存名称需要哪种实现?
不是基于缓存名称,而是基于CacheManager(可能),将其中之一声明为Primary CacheManager,如下所示:
Primary CacheManager
@Configuration @EnableCaching @PropertySource(value = { "classpath:/cache.properties" }) public class CacheConfig { @Bean @Primary public CacheManager hazelcastCacheManager() { ClientConfig config = new ClientConfig(); HazelcastInstance client = HazelcastClient.newHazelcastClient(config); return new HazelcastCacheManager(client); } @Bean public CacheManager guavaCacheManager() { GuavaCacheManager cacheManager = new GuavaCacheManager("mycache"); CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterWrite(10, TimeUnit.MINUTES); cacheManager.setCacheBuilder(cacheBuilder); return cacheManager; } }
并在课程级别将其指定为:
@Service @CacheConfig(cacheManager="hazelcastCacheManager") public class EmployeeServiceImpl implements IEmployeeService { }
或在方法级别上为:
@Service public class EmployeeServiceImpl implements IEmployeeService { @Override @Cacheable(value = "EMPLOYEE_", key = "#id", cacheManager= "guavaCacheManager") public Employee getEmployee(int id) { return new Employee(id, "A"); } }
如果只需要保留缓存名称,则可以使用多个CacheManager。