publicclassCacheErrorLoggingHandlerextendsSimpleCacheErrorHandler{privateLoggerlogger=LoggerFactory.getLogger(CacheErrorLoggingHandler.class);privateClientResourcesclientResources;publicvoidsetClientResources(ClientResourcesclientResources){this.clientResources=clientResources;}@OverridepublicvoidhandleCacheGetError(RuntimeExceptionexception,Cachecache,Objectkey){logger.error("Fail to get cache with key [{}]",key,exception);}@OverridepublicvoidhandleCachePutError(RuntimeExceptionexception,Cachecache,Objectkey,Objectvalue){logger.error("Fail to put cache with key [{}]",key,exception);}@OverridepublicvoidhandleCacheEvictError(RuntimeExceptionexception,Cachecache,Objectkey){logger.error("Fail to evict cache with key [{}]",key,exception);}@OverridepublicvoidhandleCacheClearError(RuntimeExceptionexception,Cachecache){logger.error("Fail to clear cache",exception);}}
另外需要注意,不是直接 @Component 的方式注入 Spring 容器,而是需要在缓存配置类中配置:
publicclassCustomCompositeCacheManagerimplementsCacheManager,InitializingBean{privatefinalLoggerlogger=LoggerFactory.getLogger(CustomCompositeCacheManager.class);privateLinkedList<CacheManager>cacheManagers=newLinkedList<>();privateCacheManagerredisCacheManager;privatebooleanfallbackToNoOpCache=false;publicCustomCompositeCacheManager(){}publicCustomCompositeCacheManager(CacheManager...cacheManagers){addCacheManagers(Arrays.asList(cacheManagers));}@Override@NullablepublicCachegetCache(Stringname){for(CacheManagercacheManager:this.cacheManagers){Cachecache=cacheManager.getCache(name);if(cache!=null){returncache;}}returnnull;}@OverridepublicCollection<String>getCacheNames(){Set<String>names=newLinkedHashSet<>();for(CacheManagermanager:this.cacheManagers){names.addAll(manager.getCacheNames());}returnCollections.unmodifiableSet(names);}@OverridepublicvoidafterPropertiesSet()throwsException{if(this.fallbackToNoOpCache){this.cacheManagers.add(newNoOpCacheManager());}}publicvoidsetFallbackToNoOpCache(booleanfallbackToNoOpCache){this.fallbackToNoOpCache=fallbackToNoOpCache;}publicvoidaddCacheManagers(Collection<CacheManager>cacheManagers){this.cacheManagers.addAll(cacheManagers);redisCacheManager=this.cacheManagers.get(0);}publicvoiddeactivateRedisCacheManager(){if(!cacheManagers.getFirst().equals(redisCacheManager)){logger.warn("First cache manager is not redis cache manager");return;}cacheManagers.removeFirst();}publicvoidactivateRedisCacheManager(){if(cacheManagers.getFirst().equals(redisCacheManager)){logger.warn("First cache manager already is redis cache manager");return;}cacheManagers.addFirst(redisCacheManager);}}