Si está utilizando Spring Data Redis, puede aprovechar el soporte de Spring para manejar estas interrupciones temporales y excepciones a través de un controlador de excepciones personalizado.
Código:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Recomendamos establecer el tiempo de espera más bajo que el predeterminado (60000):
spring.cache.type=redis
spring.redis.timeout=100
A continuación, cree un controlador de errores personalizado en el contexto de Spring:
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.context.annotation.Configuration;
@Slf4j
@EnableCaching
@Configuration
public class CacheConfiguration extends CachingConfigurerSupport {
@Override
public CacheErrorHandler errorHandler() {
return new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
log.info("Failure getting from cache: " + cache.getName() + ", exception: " + exception.toString());
}
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
log.info("Failure putting into cache: " + cache.getName() + ", exception: " + exception.toString());
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
log.info("Failure evicting from cache: " + cache.getName() + ", exception: " + exception.toString());
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
log.info("Failure clearing cache: " + cache.getName() + ", exception: " + exception.toString());
}
};
}
}
Spring debería detectar la falla después de 100 milisegundos y retroceder para recuperar los datos recuperados a través de @Cacheable
métodos anotados normalmente como si hubiera un error de caché. Y siempre que se restablezca la memoria caché, Spring comenzará a extraer de la memoria caché nuevamente.