2017-02-13 34 views
0

當應用程序啓動時,我想創建EhCache Manager並自動將可用CacheEntryFactories分配給緩存自我填充區域。以編程方式在啓動時創建EHCACHE自填充緩存

所以手術順序是:

  1. 找到ehcache.xml配置
  2. 創建的CacheManager實例
  3. 檢測CacheEntryFactories可能被分配
  4. 創建和使用這些工廠

回答

0

更換selfPopulatingCaches我解決了這個問題所有工廠都放在一個包中,用給定的模式命名並使用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緩存區域。

相關問題