加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:38:15 所属栏目:大数据 来源:网络整理
导读:我正在开发一个Spring Boot应用程序,我需要使用分布式(例如Hazelcast)和本地(例如Guava)缓存.有没有办法配置Spring Cache在使用@Cacheable时使用它们并根据缓存名称决定需要哪个实现? 我尝试为HZ和Guava创建一个配置来定义里面的缓存名称,但是Spring抱怨它

我正在开发一个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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读