gpt4 book ai didi

java - 如何在没有xml的情况下使用spring boot 2和ehcache 3?

转载 作者:行者123 更新时间:2023-11-29 04:07:05 25 4
gpt4 key购买 nike

现在我有以下配置:

@Configuration
@EnableCaching
public class EhcacheConfig {
@Bean
public CacheManager cacheManager() throws URISyntaxException {
return new JCacheCacheManager(Caching.getCachingProvider().getCacheManager(
getClass().getResource("/ehcache.xml").toURI(),
getClass().getClassLoader()
));
}
}

它引用了以下 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">

<cache alias="pow_cache">
<key-type>org.springframework.cache.interceptor.SimpleKey</key-type>
<value-type>java.lang.Double</value-type>
<expiry>
<ttl unit="seconds">15</ttl>
</expiry>

<listeners>
<listener>
<class>my.pack.CacheEventLogger</class>
<event-firing-mode>ASYNCHRONOUS</event-firing-mode>
<event-ordering-mode>UNORDERED</event-ordering-mode>
<events-to-fire-on>CREATED</events-to-fire-on>
<events-to-fire-on>EXPIRED</events-to-fire-on>
</listener>
</listeners>

<resources>
<heap unit="entries">2</heap>
<offheap unit="MB">10</offheap>
</resources>
</cache>

</config>

服务看起来像这样:

@Cacheable(value = "pow_cache", unless = "#pow==3||#result>100", condition = "#val<5")
public Double pow(int val, int pow) throws InterruptedException {
System.out.println(String.format("REAL invocation myService.pow(%s, %s)", val, pow));
Thread.sleep(3000);
return Math.pow(val, pow);
}

它工作正常,但我想摆脱 xml 配置。

我已阅读并尝试申请 following answer (最后一段代码)但它仅适用于 Ehcache 2 但我将使用 Eehcache 3

我怎样才能实现它?

最佳答案

作为 EhCache seems to be JSR-107 compliant ,您需要以这种方式使用它来进行编程配置:

@Bean
public CacheManager cacheManager() throws URISyntaxException {
CachingProvider provider = Caching.getCachingProvider();
CacheManager cacheManager = provider.getCacheManager();

CacheConfigurationBuilder<SimpleKey, Double> configuration =
CacheConfigurationBuilder.newCacheConfigurationBuilder(org.springframework.cache.interceptor.SimpleKey.class,
java.lang.Double.class,
ResourcePoolsBuilder.heap(2).offheap(10, MemoryUnit.MB))
.withExpiry(Expirations.timeToLiveExpiration(new Duration(15, TimeUnit.SECONDS)));

Cache cache = cacheManager.createCache("pow_cache", configuration);
cache.getRuntimeConfiguration().registerCacheEventListener(listener, EventOrdering.UNORDERED,
EventFiring.ASYNCHRONOUS, EnumSet.of(EventType.CREATED, EventType.EXPIRED));
return cacheManager;
}

我自己还没有测试过,但这应该适合你。

查看 this programatic sample with more configuration options来自 EhCache 存储库和 how to register listeners programatically 上的文档部分也是。

关于java - 如何在没有xml的情况下使用spring boot 2和ehcache 3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57909228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com