【问题标题】:Creating a CacheManager from an XMLConfiguration using a StatisticsService使用 StatisticsService 从 XMLConfiguration 创建 CacheManager
【发布时间】:2020-02-04 16:54:26
【问题描述】:

我知道如何在 org.ehcache:ehcache:3.8.1 中使用XMLConfiguration 创建CacheManager:

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();

我也知道如何用StatisticsService 创建CacheManager:

StatisticsService statisticsService = new DefaultStatisticsService();
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(statisticsService)
      .build();
cacheManager.init();

但是如何使用StatisticsService 从XMLConfiguration 创建CacheManager?

【问题讨论】:

    标签: ehcache ehcache-3


    【解决方案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. 键类型和值类型分别为Long和String……​

    5. 配置为通过引用(而不是通过值)存储缓存条目...​

    6. 从那一刻起为条目定义一分钟的到期时间,然后创建它们。

    7. 使用缓存管理器,使用在步骤中创建的配置创建一个名为jCache的缓存>

    8. 将一些数据放入缓存中。

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

    【讨论】:

      【解决方案2】:

      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);
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多