@Component public class MyCacheDecoratorFactory extends CacheDecoratorFactory { @Autowired private MyUpdatingCacheEntryFactory myUpdatingCacheEntryFactory; @Override public Ehcache createDecoratedEhcache(final Ehcache ehcache, final Properties properties) { final SelfPopulatingCache selfPopulatingCache = new UpdatingSelfPopulatingCache(ehcache, myUpdatingCacheEntryFactory); selfPopulatingCache.setTimeoutMillis(30 * 1000); return selfPopulatingCache; } @Override public Ehcache createDefaultDecoratedEhcache(final Ehcache ehcache, final Properties properties) { return this.createDecoratedEhcache(ehcache, properties); } }
/** * Replace the cache with a SelfPopulatingCache decorated one if this has not been done yet. * The cacheLoaderTimeoutMillis of the original cache will be used as the timeoutMillis of the BlockingCache. * @param ehcache the original cache * @param factory the cache entry value factory * @return a BlockingCache wrapping the original one */ protected SelfPopulatingCache replaceWithSelfPopulatingCacheIfNot(Ehcache ehcache, CacheEntryFactory factory){ if (ehcache instanceof SelfPopulatingCache){ return (SelfPopulatingCache) ehcache; } SelfPopulatingCache selfPopulatingCache = new SelfPopulatingCache(ehcache, factory); selfPopulatingCache.setTimeoutMillis((int)ehcache.getCacheConfiguration().getCacheLoaderTimeoutMillis()); cacheManager.replaceCacheWithDecoratedCache(ehcache, selfPopulatingCache); return selfPopulatingCache; }
/** * Create a new {@link SelfPopulatingCache} and corresponding {@link CacheEntryFactory} */ protected SelfPopulatingCacheTracker createSelfPopulatingCache(Ehcache cache, int timeout, DecoratedCacheType type, long refreshinterval) { final SelfPopulatingCache selfPopulatingCache; final ThreadLocal<MethodInvocation> invocationLocal; switch (type) { case REFRESHING_SELF_POPULATING_CACHE: { final RefreshingCacheEntryFactory cacheEntryFactory = new RefreshingCacheEntryFactory(); selfPopulatingCache = new RefreshingSelfPopulatingCache(cache, cacheEntryFactory, scheduler, executor, refreshinterval); invocationLocal = cacheEntryFactory.entryFactory; break; } case SELF_POPULATING_CACHE: { final ThreadLocalCacheEntryFactory cacheEntryFactory = new ThreadLocalCacheEntryFactory(); selfPopulatingCache = new SelfPopulatingCache(cache, cacheEntryFactory); invocationLocal = cacheEntryFactory.entryFactory; break; } default: { throw new IllegalArgumentException("DecoratedCacheType " + type + " is not a supported self-populating type"); } } selfPopulatingCache.setTimeoutMillis(timeout); return new SelfPopulatingCacheTracker(selfPopulatingCache, invocationLocal); }