skip to Main Content

We are developing an application that uses the Redis server as a cache server.
So what We do are when a client request API it first go to Redis to get data if there is no data it returns null so the second step go to the MYSQL database to get data,
But the problem when we lose the Redis connection it returns JedisConnectionException.
Can we handle this exception in configuration to return null instead of exception if there is no connection?

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }

    @Bean
    HashOperations hashOperations() {
        return redisTemplate().opsForHash();
    }
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private HashOperations hashOperations;


    public void save(User user) {
        hashOperations.put("USER",user.getId(),user);
    }

    public List<User> getAll() {
        Collection users = hashOperations.entries("USER").values();
        if(CollectionUtils.isEmpty(users)){
            // get data from data base
        }
        return (List<User>) users;
    }

2

Answers


  1. Chosen as BEST ANSWER
    private static boolean isConnected() {
            try {
                // get any fake key to test connection  
                ApplicationContextConfig.getBean(HashOperations.class).get("TEST", 1); 
                return true;
            } catch (Exception ex) {
                return false;
            }
        }
    

    Note that Exception may by RedisConnectionFailureException or JedisConnectionException So I made it Exception.
    This method is called before any Redis operations to test connectivity first.


  2. Maybe using try block?

    try {
        // your Redis operations
    } catch (JedisConnectionException jce) {
        return null;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search