我知道如何在org.ehcache:ehcache:3.8.1中使用CacheManager
创建一个XMLConfiguration
:
import org.ehcache.config.Configuration;
import org.ehcache.xml.XmlConfiguration;
import org.ehcache.config.builders.CacheManagerBuilder;
.
.
.
URL myUrl = CacheUtil.class.getResource("/my-config.xml");
Configuration xmlConfig = new XmlConfiguration(myUrl);
cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
cacheManager.init();
我也知道如何使用CacheManager
创建一个StatisticsService
:
StatisticsService statisticsService = new DefaultStatisticsService();
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.using(statisticsService)
.build();
cacheManager.init();
但是如何使用CacheManager
从XMLConfiguration
创建StatisticsService
?
答案 0 :(得分:1)
以下是示例代码,演示了基本JCache配置API的用法:
CachingProvider provider = Caching.getCachingProvider();
CacheManager cacheManager = provider.getCacheManager();
MutableConfiguration<Long, String> configuration =
new MutableConfiguration<Long, String>()
.setTypes(Long.class, String.class)
.setStoreByValue(false)
.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));
Cache<Long, String> cache = cacheManager.createCache("jCache", configuration);
cache.put(1L, "one");
String value = cache.get(1L);
从应用程序的类路径中检索默认的CachingProvider
实现。仅在类路径中只有一个JCache实现jar时,此方法才有效。如果您的类路径中有多个提供程序,请使用完全限定的名称org.ehcache.jsr107.EhcacheCachingProvider
来检索Ehcache缓存提供程序。您可以改为使用Caching.getCachingProvider(String)
静态方法来做到这一点。
使用提供程序检索默认的CacheManager
实例。
使用MutableConfiguration
,其键类型和值类型分别为Long
和String
………
配置为按引用存储缓存条目(不是按值存储)...
,并且从那时起为条目定义的有效时间为一分钟,便会创建它们。
使用缓存管理器,使用在步骤<3>
jCache
的缓存。
将一些数据放入缓存。
答案 1 :(得分:0)
类EhcacheManager
中有一个带有2个参数的构造函数:
public EhcacheManager(Configuration config, Collection<Service> services)
您可以按以下方式使用它:
URL myUrl = CacheUtil.class.getResource("/my-config.xml");
Configuration xmlConfig = new XmlConfiguration(myUrl);
StatisticsService statisticsService = new DefaultStatisticsService();
Set<Service> services = new HashSet<>();
services.add(statisticsService);
cacheManager = new EhcacheManager(xmlConfig, services);