I'm working with ehcache 2.5.4.
I have an object that needs to be cached through out the day and refreshed with a new value at 00:00am every day.
Currently with ehcache configurations I can only set the time to live and time to idle, but that will depend on the time I created the object or when it's used. ie:
<cache
name="cache.expiry.application.date_status"
maxElementsInMemory="10"
eternal="false"
timeToIdleSeconds="60"
timeToLiveSeconds="50" />
Is there a way to get ehcache to expire specific caches based on specific times.
With Ehcache 3.2 I implemented an Expiry extension.
Now, I have logging etc as well but I minimalized my code for cleanness.
Then you just need to configure it in your configuration builder.
Clearly Ehcache improved on there API's somewhat from 2.5 to 3.2 as you don't need to create your own 'element' and ensure it's usage to initiate expiry or eviction policies. The policies are now cache bound.
I've done this by extending Ehcache's
Element
class like so:The rest is as easy as putting new instance of
EvictOnGivenTimestampElement
object into the cache instead ofElement
.Advantage of this approach is that you don't have to worry about external cronjobs, etc. And the obvious disadvantage is the attachment to Ehcache API which I hope won't change too often.
EHCache only supports eviction after a certain period of time (either being in the cache or due to inactivity). However, you should be able to accomplish that fairly easily by scheduling the removal with something like this:
This basic example uses the Java Timer class to illustrate, but any scheduler could be utilized. Every 24 hours, starting from midnight - this would run and remove all the elements from the specified cache. The actual
run
method could be modified to remove elements matching a certain criteria as well.You'd just need to make sure you start it when the application is started.