首页 > 解决方案 > 如何监听 ehcache clear 事件?

问题描述

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

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

缓存事件侦听器仅用于入口范围操作,但我想侦听整个缓存清除事件。

标签: javaehcachejcache

解决方案


使用 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 );
    }
}

用法:

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

推荐阅读