0

我使用过 Ehcache 3,而且我是 Ehcache 3 的新手,我有一个缓存管理器,如下所示:

 private CacheManager cacheManager;

现在当对象被创建时 cacheManager 被初始化:

public ListPlanImpl() {
        System.out.println("constructore being initalized");
        System.getProperties().setProperty("java -Dnet.sf.ehcache.use.classic.lru", "true");
        cacheManager = CacheManagerBuilder
                .newCacheManagerBuilder().build();
        cacheManager.init();


    }

初始化缓存管理器后,这是我的主类,所有获取和放入缓存的操作都在其中发生。我已将多个数据插入不同的缓存,例如:

     @Stateless
        public class ListPlanImpl implements CachePlan,ListPlan {

         private static final String CACHE_OPERATING_PARAMETER = "cache_key_operating_parameter";
            private static final String CACHE_SECURITY_PARAMETER = "cache_security";
      private static Cache<String, GenericClassForList> operatingParametersCache;
        private static Cache<String, GenericClassForList> securitiesTradingParameterCache;

         public void putInCache() throws ExecutionException, InterruptedException {
                System.out.println("putting in list");

                this.operatingParametersCache = cacheManager
                        .createCache("cacheOfOperatingParameters", CacheConfigurationBuilder
                                .newCacheConfigurationBuilder(
                                        String.class, GenericClassForList.class,
                                        ResourcePoolsBuilder.heap(1000000000)).withExpiry(Expirations.timeToLiveExpiration(Duration.of(60000,
                                        TimeUnit.SECONDS))));

                operatingParametersCache.put(CACHE_OPERATING_PARAMETER, new GenericClassForList(this.operatingParamService.getOperatingParamDTO()));


                this.securitiesTradingParameterCache = cacheManager
                        .createCache("cacheOfSecurityTrading", CacheConfigurationBuilder
                                .newCacheConfigurationBuilder(
                                        String.class, GenericClassForList.class,
                                        ResourcePoolsBuilder.heap(1000000000)).withExpiry(Expirations.timeToLiveExpiration(Duration.of(60000,
                                        TimeUnit.SECONDS))));
  securitiesTradingParameterCache.put(CACHE_SECURITY_PARAMETER, new GenericClassForList(this.securitiesTradingParamsService.getSecuritiesTradingParamDTO()));

            }
        }

我想要一个单独的函数,它将返回所有缓存名称和缓存中数据总数的计数,以便我可以在 UI 中显示包含数据的缓存。我搜索了问题,但没有找到解决方案。

4

1 回答 1

1

Cache实现Iterable<Cache.Entry<K,V>>,因此您可以遍历条目以获取每个缓存的键和值,例如:

for( Cache.Entry<String, GenericClassForList> entry : operatingParametersCache) { 
  String key = entry.getKey(); 
  GenericClassForList value = entry.getValue(); 
  //if counting just increasing a counter might be sufficient, 
  //otherwise use the key and value as needed 
}

由于您已经引用了缓存,只需将该方法应用于每个单独的缓存。

如果您没有方便的参考资料,您可以在缓存的已用别名上保留一些注册表(您提供了别名,以便您可以使用这些别名从缓存管理器中获取缓存)。如果您不能这样做,您可能需要跟踪提供给缓存管理器的别名,例如通过用委托包装它。

于 2019-09-19T11:30:58.643 回答