当我使用Spring数据Redis流水线时,Spring启动应用程序冻结

时间:2016-10-26 16:17:41

标签: java spring-boot spring-data-redis

我有一个使用Redis进行缓存的Spring启动应用程序。我正在尝试使用Redis流水线技术在一次调用中获取多个信息。在我的@Configuration课程中,我有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;
}

然后我尝试使用流水线技术从Redis获取多个值并将其放在HashMap中,如下所示:

@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){}

}
}

通常情况下,这样可以正常工作并按预期返回值。但是,当我的应用程序收到大量请求时,由于某种原因,应用程序会冻结。但是,当我删除流水线,并单独获取值时,应用程序工作正常。为什么应用冻结了?我是redis流水线的新手,所以我的代码效率可能不高。

感谢。

0 个答案:

没有答案