首页 > 解决方案 > Ehcache jsr107:默认值不适用于以编程方式创建的缓存

问题描述

根据我在之前的SO question中的发现,我正在尝试以声明式和命令式配置的混合设置 JCache,以声明式地限制缓存的最大大小。

我在我的 application.yaml 中保留了缓存列表和它们的条目的持续时间 (TTL),这是通过属性加载器获得的。然后我使用下面的代码创建我的缓存:

@Bean
public List<javax.cache.Cache<Object, Object>> getCaches() {
    javax.cache.CacheManager cacheManager = this.getCacheManager();
    List<Cache<Object, Object>> caches = new ArrayList();
    Map<String, String> cacheconfigs = //I populate this with a list of cache names and durations;
    Set<String> keySet = cacheconfigs.keySet();
    Iterator i$ = keySet.iterator();

    while(i$.hasNext()) {
        String key = (String)i$.next();
        String durationMinutes = (String)cacheconfigs.get(key);
         caches.add((new GenericDefaultCacheConfigurator.GenericDefaultCacheConfig(key, new Duration(TimeUnit.MINUTES, Long.valueOf(durationMinutes)))).getCache(cacheManager));
    }

    return caches;
}

@Bean
public CacheManager getCacheManager() {
    return Caching.getCachingProvider().getCacheManager();
}

private class GenericDefaultCacheConfig {
    public GenericDefaultCacheConfig(String cacheName, Duration duration) {
        public GenericDefaultCacheConfig(String id, Duration duration, Factory expiryPolicyFactory) {
        CACHE_ID = id;
        DURATION = duration;
        EXPIRY_POLICY = expiryPolicyFactory;
    }
    private MutableConfiguration<Object, Object> getCacheConfiguration() {
        return new MutableConfiguration<Object, Object>()
                    .setTypes(Object.class, Object.class)
                    .setStoreByValue(true)
                    .setExpiryPolicyFactory(EXPIRY_POLICY);
    }
    public Cache<Object, Object> getCache(CacheManager cacheManager) {
        CacheManager cm = cacheManager;
        Cache<K, V> cache = cm.getCache(CACHE_ID, Object.class, Object.class);
        if (cache == null)
           cache = cm.createCache(CACHE_ID, getCacheConfiguration());
        return cache;
    }
}

我尝试使用以下 ehcache.xml 限制缓存大小:

<config
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
    xsi:schemaLocation="
    http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
    http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

<service>
    <jsr107:defaults default-template="heap-cache" enable-management="true" enable-statistics="true">
    </jsr107:defaults>
</service>

<cache-template name="heap-cache">
    <resources>
        <heap unit="entries">20</heap>
    </resources>
</cache-template> </config>

我在 application.yaml 中设置了以下声明:

spring:
  cache:
    jcache:
      config: classpath:ehcache.xml

但是,我的缓存不遵守强加的限制。我通过以下测试进行验证:

    @Test
public void testGetCacheMaxSize() { 
    Cache<Object, Object> cache = getCache(MY_CACHE); //I get a cache of type Eh107Cache[myCache]

    CacheRuntimeConfiguration<Object, Object> ehcacheConfig = (CacheRuntimeConfiguration<Object, Object>)cache.getConfiguration(
            Eh107Configuration.class).unwrap(CacheRuntimeConfiguration.class);
    long size = ehcacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(); //Returns 9223372036854775807 instead of the expected 20

    for(int i=0; i<30; i++)
        commonDataService.getAllStates("ENTRY_"+i);

    Map<Object, Object> cachedElements = cacheManagerService.getCachedElements(MY_CACHE);
    assertTrue(cachedElements.size().equals(20)); //size() returns 30
}

有人可以指出我做错了什么吗?提前致谢。

标签: spring-bootehcacheconfiguration-filesjcache

解决方案


问题来自于将缓存管理器设置为:

Caching.getCachingProvider().getCacheManager();

通过在缓存管理器的初始化上设置配置文件 URI,我让它工作:

cachingProvider = Caching.getCachingProvider();
configFileURI = resourceLoader.getResource(configFilePath).getURI();
cacheManager = cachingProvider.getCacheManager(configFileURI, cachingProvider.getDefaultClassLoader());

我期望 Spring Boot 会根据属性spring.cache.jcache.config中包含的配置文件自动创建缓存管理器,但事实并非如此,因为我得到了如上所述的缓存管理器,而不是简单的 auto - 连接它并让 Spring 创建它。


推荐阅读