以编程方式在启动时创建EHCACHE自填充缓存

时间:2017-02-13 13:36:01

标签: java reflection ehcache

当应用程序启动时,我想创建EhCache Manager并自动将可用的CacheEntryFactories分配给缓存区域以进行自我填充。

所以操作顺序是:

  1. 找到ehcache.xml配置
  2. 创建CacheManager实例
  3. 检测可以分配的CacheEntryFactories
  4. 使用这些工厂创建和替换selfPopulatingCaches

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,将所有工厂放在一个包中,用给定的模式命名它们并使用reflection创建实例,创建SelfPopulatingCaches并使用replaceCacheWithDecoratedCache()替换它们。这是代码片段:

File configurationFile = new File(EHCACHE_CONFIG_PATH);
Configuration configuration = ConfigurationFactory.parseConfiguration(configurationFile);   
CacheManager manager = CacheManager.create(configuration);

for(String cacheName : manager.getCacheNames()){

    Cache cache = manager.getCache(cacheName);

    try {

        Ehcache selfPopulatingCache = createSelfPopulatingCache(cache);

        if(selfPopulatingCache != null){
            manager.replaceCacheWithDecoratedCache(cache, selfPopulatingCache);
            log.info("Factory for cache '" + cache.getName() + "' created.");
        }           

    } catch (Exception e) {
        log.error("Error creating self-populating-cache for '" + cache.getName() + "'", e);
    }

}


private Ehcache createSelfPopulatingCache(Ehcache cache) throws Exception{

    CacheEntryFactory factory = null;

    String factoryClassName = "com.myproject.factories." + Utils.capitalize(cache.getName()) + "CacheFactory";

    Class factoryClass;
    try {

        factoryClass = Class.forName(factoryClassName);

    } catch (Exception e) {
        log.debug("Unable to find factory for cache " + cache.getName());
        return null;
    }

    /**
     * factory may need some extra resource (dataSource, parameters)
     * organize factories in abstract classes with their constructors
     * and ask for factoryClass.getSuperclass() i.e:
     *
     *  if(factoryClass.getSuperclass().equals(AbstractDatabaseCacheFactory.class)){
     *      Constructor constructor = factoryClass.getConstructor(DataSource.class);
     *      factory = (CacheEntryFactory)constructor.newInstance(DataSourceListener.getDataSourceMaster());
     *  }
     *
     */
    Constructor constructor = factoryClass.getConstructor();
    factory = (CacheEntryFactory)constructor.newInstance();

    return new SelfPopulatingCache(cache, factory);

}    
com.myproject.factories中的

我会把类似

的类
AccountsCacheFactory.java
EmployersCacheFactory.java
BlogPostsCachFactory.java

这将是accountsemployersblogPosts缓存区域的工厂。