当应用程序启动时,我想创建EhCache Manager
并自动将可用的CacheEntryFactories
分配给缓存区域以进行自我填充。
所以操作顺序是:
ehcache.xml
配置CacheEntryFactories
selfPopulatingCaches
答案 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
这将是accounts
,employers
和blogPosts
缓存区域的工厂。