Spring Data Redis issue with connection pooling

2.6k views Asked by At

I am using Spring Data Redis and need have an issue with JedisPoolConfig. I have configured a RedisTemplate as follows:

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

I have a service that is marked as @Transactional, which in turns calls a @Repository that increments a number of keys in 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);
    }
}

When I call myService.recordStats() and step through the code in debug, it hangs upon trying to increment KEY11, and ultimately fails with redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool. If I amend the JedisPoolConfig to increase the MaxTotal as follows:

@Bean
JedisPoolConfig jedisPoolConfig() {

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

Then the problem goes away, and I can increment all 11 keys in a transaction. It seems to be the case that every valueOperations.increment call is taking another connection from the pool. Is this correct, or do I have a configuration problem somewhere?

0

There are 0 answers