Spring Data Redis问题与连接池有关

时间:2015-06-17 22:34:29

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

我正在使用Spring Data Redis,但JedisPoolConfig需要遇到问题。我已按如下方式配置RedisTemplate

@Bean
JedisPoolConfig jedisPoolConfig() {

    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    return jedisPoolConfig;
}

@Bean
public RedisConnectionFactory redisConnectionFactory() {

    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig());
    jedisConnectionFactory.setHostName(redisSettings.getServer().getHost());
    jedisConnectionFactory.setPort(redisSettings.getServer().getPort());
    return jedisConnectionFactory;
}

@Bean
public RedisTemplate<String, Integer> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

    RedisTemplate<String, Integer> redisTemplate = new RedisTemplate<String, Integer>();
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setEnableTransactionSupport(true);
    return redisTemplate;
}

我有一个标记为@Transactional的服务,该服务又调用@Repository来增加Redis中的一些键:

@Service
@Transactional
public class MyService {

    @Autowired
    MyRepository myRepository;

    public void recordStats() {

        myRepository.recordStats();
    }

}


@Repository
public class MyRepository {

    @Resource(name="redisTemplate")
    ValueOperations<String, Integer> valueOperations;

    public void recordStats() {

        valueOperations.increment("KEY01", 1);
        valueOperations.increment("KEY02", 1);
        valueOperations.increment("KEY03", 1);
        valueOperations.increment("KEY04", 1);
        valueOperations.increment("KEY05", 1);
        valueOperations.increment("KEY06", 1);
        valueOperations.increment("KEY07", 1);
        valueOperations.increment("KEY08", 1);
        valueOperations.increment("KEY09", 1);
        valueOperations.increment("KEY10", 1);
        valueOperations.increment("KEY11", 1);
    }
}

当我调用myService.recordStats()并在调试中逐步执行代码时,它会在尝试增加KEY11时挂起,最终会因redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool而失败。如果我修改JedisPoolConfig以增加MaxTotal,如下所示:

@Bean
JedisPoolConfig jedisPoolConfig() {

    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    jedisPoolConfig.setMaxTotal(128);
    return jedisPoolConfig;
}

然后问题就消失了,我可以在事务中增加所有11个键。似乎每个valueOperations.increment调用都从池中获取另一个连接。这是正确的,还是我在某处遇到配置问题?

0 个答案:

没有答案