将多个缓存实现与 Spring 缓存一起使用

Using multiple cache implementations with Spring Cache

我正在开发一个 Spring Boot 应用程序,我需要在其中使用分布式(例如 Hazelcast)和本地(例如 Guava)缓存。有没有办法配置 Spring 缓存在使用 @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<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
           .maximumSize(100)
           .expireAfterWrite(10, TimeUnit.MINUTES);
           cacheManager.setCacheBuilder(cacheBuilder);
           return cacheManager;
    }

}

并在 class 级别指定为:

@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。

你有2个选项。

一个是@Arpit 提到的:定义多个 CacheManager 并在方法级注释(@Cacheable、@CachePut 等)或 class 级注释(@CacheConfig)中指定它

您还可以创建自定义注释:

@CacheConfig(cacheManager = "guavaCacheManager")
@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface GuavaCacheable {
}

@GuavaCacheable
@Service
public class MyServiceImpl implements MyService {
}

作为第二个选项,如果您的缓存需求很复杂,您可以创建自定义缓存解析器。

您可以查找 here 管理多个 CacheManager 并支持 enabling/disabling 的自定义 CacheResolver。但在大多数情况下,CacheResolver 是大材小用。

可以考虑使用

https://github.com/yatharthamishra0419/multimodule-cache

用于支持多个缓存系统的库,这个库是可扩展的,multi-module 可以在 framework.This 中添加对各种缓存系统的感知和支持,还包括一个注释,通过它可以有多个源使用