0

我想使用 Ehcache 使用 read-through 和 write-through 缓存策略,并且我正在使用 XML 配置来配置 Ehcache,我想将 spring bean(CacheLoaderWriter 实现)设置为缓存配置,我不能使用 XML 配置来做到这一点,因为然后 Ehcache 使用默认构造函数实例化 bean,spring DI 将不起作用,那么,如何覆盖/设置 spring 托管的 CacheLoaderWriter bean 以缓存在 java-config 的 XML 配置文件中定义?

我尝试在我的 XML 文件中设置 CacheLoaderWriter 类,如下所示

<cache alias="employeeEntityCache">
     <key-type>java.lang.Long</key-type>
     <value-type>com.example.spring.cahce.model.Employee</value-type>
     <loader-writer>
<class>com.example.spring.cahce.stragegy.readwritethrough.EmployeeEntityLoaderWriter</class>
      </loader-writer>
      <resources>
                <heap unit="entries">100</heap>
      </resources>
</cache>

但是,然后 Ehcache 实例化 LoaderWriter bean,因此 spring DI 将不起作用

我的 java config,从 xml 加载缓存配置

    @Bean
    @Qualifier("jcachexml")
    public javax.cache.CacheManager jCacheCacheManager() {

        CachingProvider cachingProvider = Caching.getCachingProvider();
        try {
            javax.cache.CacheManager manager = cachingProvider.getCacheManager(
                    getClass().getResource("/ehcache-jsr107-config.xml").toURI(),
                    getClass().getClassLoader());
            return manager;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
     }

我想要一种方法来覆盖在 Ehcache XML 配置中设置的缓存配置,这样我就可以将 spring 管理的 CacheLoaderWriter bean 设置为缓存配置并可以使用 DI 注入依赖项

4

1 回答 1

0

Ehcache 3.8.0 增加了新特性Configuration Derivation,我们可以使用它来覆盖配置,

参考配置推导

因此,我能够通过 java config 中的 XML 配置覆盖,并将 CacheLoaderWriter 设置为完全初始化的 Spring bean。

@Autowired
private EmployeeEntityLoaderWriter employeeEntityLoaderWriter;

@Bean
@Qualifier("jcachexml")
public javax.cache.CacheManager jCacheCacheManager() {
   final XmlConfiguration xmlConfiguration = new XmlConfiguration(getClass().getResource("/ehcache-jsr107-config.xml"));
    CacheConfiguration modifiedEmployeeCacheConfiguration = xmlConfiguration.getCacheConfigurations().get("employeeEntityCache");

    // override cache configuration (specific to employee cache) from xml (Set  CacheLoderWriter)
    modifiedEmployeeCacheConfiguration = modifiedEmployeeCacheConfiguration
            .derive()
            .withLoaderWriter(employeeEntityLoaderWriter).build();

    // get updated configuration (at CacheManager level)
    org.ehcache.config.Configuration modifiedConfiguration = xmlConfiguration
            .derive()
            .withCache("employeeEntityCache", modifiedEmployeeCacheConfiguration)
            .build();

    // get CacheManager (Jcache) with above updated configuration
    final EhcacheCachingProvider ehcacheCachingProvider = (EhcacheCachingProvider) Caching.getCachingProvider();
    final javax.cache.CacheManager manager = ehcacheCachingProvider.getCacheManager(ehcacheCachingProvider.getDefaultURI(), modifiedConfiguration);

    return manager;
}
于 2019-07-25T17:12:39.630 回答