问题描述
我想在整个缓存区域被清除时收到通知。
如何为此类事件注册侦听器?
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 );