I have a Spring boot application which uses Redis for caching. I'm trying to use Redis pipelining to get multiple information in a single call. In my @Configuration
class, I have the following configuration for Redis:
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName("...");
factory.setPort("...");
factory.setUsePool(true);
return factory;
}
@Bean
RedisTemplate< String, Object > redisTemplate() {
final RedisTemplate< String, Object > template = new RedisTemplate< String, Object >();
template.setConnectionFactory( jedisConnectionFactory() );
template.setKeySerializer( new StringRedisSerializer() );
template.setHashValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
template.setValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
return template;
}
I'm then trying to use pipelining to get multiple values from Redis and put it in a HashMap as below:
@Service
class MyClass{
private HashMap<String, String> cachedEntries = null;
@Autowired
private RedisTemplate< String, Object > template;
@Autowired
private ObjectMapper mapper;
public HashMap<String, String> getCachedEntries(String key1, String key2){
if(null == cachedEntries){
cachedEntries = new HashMap<String, String>();
}
RedisCallback<Object> action = new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection connection) {
try{
cachedEntries.put("value1", template.opsForValue().get(key1).toString());
} catch(Exception e){}
try{
cachedEntries.put("value2", template.opsForValue().get(key2).toString());
} catch(Exception e){}
return null;
}
};
try{
template.executePipelined(action);
} catch(Exception e){}
}
}
Normally, this works fine and returns the values as expected. However, when my application gets lots of requests, for some reason the app freezes. But when I remove the pipelining, and get the values individually, the app works fine. Why is the app freezing? I'm new to redis pipelining, so my code might not be efficient.
Thanks.