如何处理 Spring Boot 中与缓存相关的错误?


通常,您的应用程序不太可能严重依赖缓存。事实上,您可能只是将缓存用作提高性能的一种方法。在这种情况下,即使发生与缓存相关的错误,您的应用程序也可能会顺利运行。因此,您甚至可能不会意识到缓存系统中的故障,从而难以发现它们。这就是为什么实施一个系统来正确处理与缓存相关的错误是必不可少的。
让我们看看如何在 Java 和 Kotlin 中做到这一点。
为了处理缓存失败,Spring Boot 提供了CacheErrorHandler[url=https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/interceptor/CacheErrorHandler.html] [/url]接口。通过实现它,您可以定义所需的错误处理逻辑。然后,您只需将自定义实现注册为默认错误处理程序。让我们来看看如何完成这两件事。
 
自定义错误处理逻辑
CacheErrorHandler接口提供了以下四种方法:handleCacheGetErrorhandleCachePutErrorhandleCacheEvictError,和handleCacheClearError
每一个旨在帮助您处理发生在注解的方法错误@Cachable@CachePut或者@CacheEvict,这是最重要的SpringBoot高速缓存相关的注解。
您需要做的只是实现CacheErrorHandler接口,在上述四种方法中提供错误处理逻辑。

public class CustomCacheErrorHandlerpublic class ErrorHandlingLogic implements CacheErrorHandler {
    @Override
    public void handleCacheGetError(
            RuntimeException e, 
            Cache cache, 
            Object key
    ) {
        // your custom error handling logic
    }

    @Override
    public void handleCachePutError(
            RuntimeException e, 
            Cache cache, 
            Object key, 
            Object value
    ) {
       
// your custom error handling logic
    }

    @Override
    public void handleCacheEvictError(
            RuntimeException e, 
            Cache cache, 
            Object key
    ) {
       
// your custom error handling logic
    }

    @Override
    public void handleCacheClearError(
            RuntimeException e, 
            Cache cache
    ) {
       
// your custom error handling logic
    }
}

kotlin:

class CustomCacheErrorHandler : CacheErrorHandler {
    override fun handleCacheGetError(
        exception: RuntimeException,
        cache: Cache,
        key: Any
    ) {
        // your custom error handling logic
    }

    override fun handleCachePutError(
        exception: RuntimeException,
        cache: Cache,
        key: Any,
        value: Any?
    ) {
       
// your custom error handling logic
    }

    override fun handleCacheEvictError(
        exception: RuntimeException,
        cache: Cache,
        key: Any
    ) {
       
// your custom error handling logic
    }

    override fun handleCacheClearError(
        exception: RuntimeException,
        cache: Cache
    ) {
       
// your custom error handling logic
    }
}

这样,您可以记录与缓存相关的错误,不再忽略它们,或者在发生致命异常时将它们发送回客户端。
 

注册您的自定义 CacheErrorHandler 实现
现在,您必须定义一个CustomachingConfiguration继承CachingConfigurerSupport. 覆盖它的errorHandler方法并确保返回CustomCacheErrorHandler上面定义的类的实例。

@Configuration
public class CustomCachingConfiguration extends CachingConfigurerSupport {  
    @Override
    public CacheErrorHandler errorHandler() {
        return new CustomCacheErrorHandler();
    }
    
    // ...
}

kotlin:
@Configuration
class CustomCachingConfiguration : CachingConfigurerSupport() {
    override fun errorHandler(): CacheErrorHandler {
        return CustomCacheErrorHandler()
    }

    // ...
}

您的应用程序现在可以免受与缓存相关的故障的影响。