在Spring Cache中使用多个缓存实现 [英] Using multiple cache implementations with Spring Cache
问题描述
我正在使用Spring Boot
应用程序,需要同时使用分布式(例如Hazelcast
)和本地(例如Guava
)缓存.有没有一种方法可以配置Spring Cache在使用@Cacheable
时同时使用并根据缓存名称决定需要哪种实现?
I'm working on a Spring Boot
app where I need to use both distributed (e.g. Hazelcast
) and local (e.g. Guava
) caches. Is there a way to configure Spring Cache to use both when using @Cacheable
and decide which implementation is needed based on the cache name?
我尝试为HZ和Guava创建一个配置,以在其中定义缓存名称,但是Spring抱怨它找不到应该由HZ处理的缓存名称.当我只使用HZ或番石榴时,它们会起作用.
I tried with creating a configuration for both HZ and Guava defining the cache names inside, but Spring complains that it couldn't find the cache name that is supposed to handled by HZ. When I use exclusively HZ or Guava they work.
推荐答案
需要根据缓存名称实现哪种方式?
Which implementation is needed based on the cache name?
不是基于缓存名称,而是基于 CacheManager (可能),将其中一个声明为Primary CacheManager
,如下所示:
Not based on the cache name but yes based on CacheManager its possible, declare one of them as Primary CacheManager
, as follows:
@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.
If you have to stick on Cache name only then you can multiple CacheManager.
这篇关于在Spring Cache中使用多个缓存实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!