如何收听ehcache清除事件?

问题描述

我想在整个缓存区域被清除时收到通知

如何为此类事件注册侦听器?

Cache event listeners 仅用于入口作用域操作,但我想监听整个缓存清除事件。

解决方法

使用 aspectj 的解决方法:

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

    public enum CacheEventType {
         CLEAR,CLOSE
    }

    public void listenCacheEvent( BiConsumer<CacheEventType,?>> 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 );
    }
}

用法:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...