ehcache based on date

前端 未结 3 887
温柔的废话
温柔的废话 2021-02-08 11:58

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 12:44

    With Ehcache 3.2 I implemented an Expiry extension.

    public class EvictAtMidnightExpiry implements Expiry {
    
        @Override
        public Duration getExpiryForCreation(Object key, Object value) {
            DateTime now = new DateTime();
            DateTime resetAt = now.plusDays(1).withTimeAtStartOfDay();
            long difference = resetAt.toDateTime().getMillis() - now.getMillis();
            return Duration.of(difference, TimeUnit.MILLISECONDS);
        }
    
        @Override
        public Duration getExpiryForAccess(Object key, ValueSupplier value) {
            return null;
        }
    
        @Override
        public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) {
            return null;
        }
    }
    

    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.

    CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(1000)).withExpiry(new EvictAtMidnightExpiry()).build()
    

    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.

提交回复
热议问题