使用StatisticsService从XMLConfiguration创建CacheManager

时间:2020-02-04 16:54:26

标签: ehcache ehcache-3

我知道如何在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();

但是如何使用CacheManagerXMLConfiguration创建StatisticsService

2 个答案:

答案 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); 
  1. 从应用程序的类路径中检索默认的CachingProvider实现。仅在类路径中只有一个JCache实现jar时,此方法才有效。如果您的类路径中有多个提供程序,请使用完全限定的名称org.ehcache.jsr107.EhcacheCachingProvider来检索Ehcache缓存提供程序。您可以改为使用Caching.getCachingProvider(String)静态方法来做到这一点。

  2. 使用提供程序检索默认的CacheManager实例。

  3. 使用MutableConfiguration

  4. 创建缓存配置
  5. ,其键类型和值类型分别为LongString………

  6. 配置为按引用存储缓存条目(不是按值存储)...

  7. ,并且从那时起为条目定义的有效时间为一分钟,便会创建它们。

  8. 使用缓存管理器,使用在步骤<3>

  9. 中创建的配置创建名为jCache的缓存。
  10. 将一些数据放入缓存。

  11. 从同一缓存中检索数据。

答案 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);
相关问题