How to listen ehcache clear event?

567 Views Asked by At

I want to be notified when a whole cache region is cleared.

How can I register a listener for this type of event?

Cache event listeners are used only for entry scope operation, but I want to listen for whole cache clear event.

2

There are 2 best solutions below

0
On

Workaround using aspectj:

@Aspect
public class CacheListenerAspect {
    public Set<BiConsumer<CacheEventType, Cache<?, ?>>> listeners = new HashSet<>();

    public enum CacheEventType {
         CLEAR, CLOSE
    }

    public void listenCacheEvent( BiConsumer<CacheEventType, Cache<?, ?>> listener ) {
        listeners.add( listener );
    }

    @Around("execution(* javax.cache.Cache.*(..))")
    public Object around( ProceedingJoinPoint joinPoint ) throws Throwable {
        getEventType( joinPoint.getSignature() )
                .ifPresent( ev -> listeners.forEach( 
                        l -> l.accept( ev, (Cache<?, ?>) joinPoint.getThis() ) ) );
        return joinPoint.proceed();
    }

    public Optional<CacheEventType> getEventType( Signature signature ) {
        CacheEventType res = null;
        if (signature.getName().equalsIgnoreCase( "clear" ))
            res = CacheEventType.CLEAR;
        if (signature.getName().equalsIgnoreCase( "close" ))
            res = CacheEventType.CLOSE;
        return Optional.ofNullable( res );
    }
}

Usage:

Aspects.aspectOf( CacheListenerAspect.class ).listenCacheEvent( this::myMethod );
0
On

in ehcache version 2.x, this was done elementarily through a listener;

cache.getCacheEventNotificationService().registerListener(new CacheEventListener() {

   @Override
   public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException {
   }

   @Override
   public void notifyElementPut(Ehcache cache, Element element) throws CacheException {
   }

   @Override
   public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException {
   }

   @Override
   public void notifyElementExpired(Ehcache cache, Element element) {
   }

   @Override
   public void notifyElementEvicted(Ehcache cache, Element element) {
   }

   @Override
   public void notifyRemoveAll(Ehcache cache) {
   }

   @Override
   public void dispose() {
   }

   @Override
   public Object clone() throws CloneNotSupportedException {
       throw new CloneNotSupportedException();
   }
});

it turns out in the 3.h version, there are no more such events and have to fiddle with aspects and other redundant code?