I ran into an issue recently when my EH Caches that I wanted to create and configure using the ehcache.xml was already created. In this situation an exception is thrown by the EHCache cache manager and execution halts.
Alternatively, when it's not possible to use a configuration file ehcache.xml to define the caches, one must resort to creating them programmatically. This is the object of this post.
The code below first checks whether there is a configured cache with the given name, and if not, it proceeds to create one programmatically.
The same code above can be replaced by the following ehcache.xml below in order to create the cache myCache:
Alternatively, when it's not possible to use a configuration file ehcache.xml to define the caches, one must resort to creating them programmatically. This is the object of this post.
The code below first checks whether there is a configured cache with the given name, and if not, it proceeds to create one programmatically.
CacheFactory() { CacheManager cacheManager = CacheManager.create(); if (!cacheManager.cacheExists("myCache")) { cacheManager.addCache( new Cache( new CacheConfiguration("myCache", maxEntriesLocalHeap) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU) .eternal(false) .timeToLiveSeconds(timeToLiveSeconds) .timeToIdleSeconds(timeToIdleSeconds) ) ); } }
The same code above can be replaced by the following ehcache.xml below in order to create the cache myCache:
<ehcache> <cache name="myCache" eternal="false" maxEntriesLocalHeap="20000" timeToLiveSeconds="3600" timeToIdleSeconds="3600" memoryStoreEvictionPolicy="LRU"> </cache> </ehcache>
Comments