Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Cache with Redis - How to gracefully handle or even skip Caching in case of Connection Failure to Redis

I've enabled Caching in my Spring app and I use Redis to serve the purpose. However, whenever a connection failure occurs, the app stops working whereas I think it had better skip the Caching and go on with normal execution flow.

So, does anyone have any idea on how to gracefully do it in Spring ?

Here is the exception I got.

Caused by: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
like image 257
Peter Bean Avatar asked Dec 30 '14 15:12

Peter Bean


People also ask

Is Redis the data store for Spring Boot cache?

Overview In this short tutorial, we'll look at how to configure Redis as the data store for Spring Boot cache. Learn how we can enable multiple cache managers in our Spring Boot application.

Does Redis support caching in Java?

Redis is an open-source, in-memory data structure store that can be used to build NoSQL databases. However, Redis does not include pre-built support for either Java in general or application frameworks such as Spring. The good news is that you can perform caching with Spring and Redis by using a third-party Redis Java client, such as Redisson.

Can I use Redis with spring?

Since version 3.1, Spring has supported adding caching to existing Spring applications, in order to improve performance and decrease response times. Redis is an open-source, in-memory data structure store that can be used to build NoSQL databases.

What is @cacheable annotation in Redis?

This annotation caches data that has been fetched for the request based on configuration. Here is a controller, if you see we are caching the data coming from the database with annotation @Cacheable To make sure data gets cached with Redis server, we will need certain properties where these annotations will help us to cache the data.


2 Answers

As from Spring Framework 4.1, there is a CacheErrorHandler that you can implement to handle such exceptions. Refer to the javadoc for more details.

You can register it by having your @Configuration class extends CachingConfigurerSupport (see errorHandler()).

like image 142
Stephane Nicoll Avatar answered Oct 01 '22 11:10

Stephane Nicoll


CacheErrorHandler suggested by Stephane Nicoll is useful. But it doesn't help when it fails to create the connection to redis.

The cache method like @Cacheable stills fails with RedisConnectionFailureException.

like image 45
jeffery.yuan Avatar answered Oct 01 '22 12:10

jeffery.yuan