当无法连接到Redis时,如何在SpringBoot中设置缓存回退?

diz*_*iaq 12 spring caching redis spring-boot

有一个SpringBoot(v2.2.7)应用程序,其中配置了Redis缓存

pom.xml 的片段

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

当 Redis 服务启动并可用时,缓存将按预期工作:注释 的方法的结果@Cacheable将被缓存。不幸的是,当 Redis 服务不可用时,任何对可缓存方法的调用都会导致异常RedisConnectionFailureException: Unable to connect to Redis

我想如果应用程序可以独立于缓存可用性工作(执行业务逻辑),这是合理的。

可能的解决方案是:

  1. 自定义实现(即处理 Redis 缓存周围错误的包装器)
  2. Spring中考虑Redis缓存服务健康状况的标准配置(如果有的话)

在 SpringBoot 中设置后备缓存的正确方法是什么?