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
Note that Exception may by
RedisConnectionFailureException
orJedisConnectionException
So I made itException
.This method is called before any Redis operations to test connectivity first.
Maybe using
try
block?