Make Redis as optional

Tags: , , ,

I am using spring boot with Redis.Redis is running as Docker container


Redis is a memory DB, if it finds data in Redis based on the key, it retrieved from Redis otherwise go into actual db call. when Redis is running, code works fine. but sometimes for any reason, if Redis is down, I am getting exception RedisConnectionException: Unable to connect to localhost:6379

I want to make it optional. if it gets down, code should work as it is, by calling actual DB data(sql service repositories).

is there any way to make Redis call as optional.

if running, work with Redis, 
if down, can to actual DB without exception.

my code

@Cacheable(cacheNames = CACHE_USER_DETAILS)
    public User getUserDetails(String username) {
      //call data from sql serever via repositories.


I fixed the problem by creating own error handler and overried the spring cache error handler

package com.crif.credity.tenancy;

import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Configuration;

import com.crif.credity.config.CredityKeyGenerator;

import lombok.extern.slf4j.Slf4j;

public class CachingConfiguration extends CachingConfigurerSupport {
    public KeyGenerator keyGenerator() {
        return new CredityKeyGenerator();
    public CacheErrorHandler errorHandler() {
        return new CredityRedisCacheErrorHandler();

    public static class CredityRedisCacheErrorHandler implements CacheErrorHandler {

        public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
  "Unable to get from cache " + cache.getName() + " : " + exception.getMessage());

        public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
  "Unable to put into cache " + cache.getName() + " : " + exception.getMessage());

        public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
  "Unable to evict from cache " + cache.getName() + " : " + exception.getMessage());

        public void handleCacheClearError(RuntimeException exception, Cache cache) {
  "Unable to clean cache " + cache.getName() + " : " + exception.getMessage());

Source: stackoverflow