Skip to content
Advertisement

Can Make Redis server return NULL or False instead of JedisConnectionException?

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;
    }

Advertisement

Answer

Maybe using try block?

try {
    // your Redis operations
} catch (JedisConnectionException jce) {
    return null;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement