我正在开发一个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,如下所示:
@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
并在课程级别指定为:
@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");
}
}
如果您必须坚持使用Cache名称,那么您可以使用多个CacheManager.