Search code examples
springspring-bootjava-8jedisspring-data-redis

Configuring Jedis on Spring boot 2


I am trying to migrate from spring boot 1.5.5 to spring boot 2. I am getting the following for JedisPool

Parameter 0 of method getJedisPool in com.company.spring.config.ApplicationConfig required a bean of type 'org.springframework.data.redis.connection.jedis.JedisConnectionFactory' that could not be found.
        - Bean method 'redisConnectionFactory' in 'JedisConnectionConfiguration' not loaded because @ConditionalOnMissingBean (types: org.springframework.data.redis.connection.RedisConnectionFactory; SearchStrategy: all) found beans of type 'org.springframework.data.redis.connection.RedisConnectionFactory' redisConnectionFactory

I am trying to configure using Jedis and not lettuce. I have ignored the lettuce module when importing the spring-starter-redis-data as suggested in the docs.

The below is the code that is trying to initialize the JedisPool.

@Bean
public JedisPool getJedisPool(JedisConnectionFactory jedisConnectionFactory) {
    String host = jedisConnectionFactory.getHostName();
    int port = jedisConnectionFactory.getPort();
    String password = StringUtils.isEmpty(jedisConnectionFactory.getPassword()) ? null : jedisConnectionFactory.getPassword();
    int timeout = jedisConnectionFactory.getTimeout();
    GenericObjectPoolConfig poolConfig = jedisConnectionFactory.getPoolConfig();
    log.info("Starting Redis with Host:{}, Port:{}, Timeout:{}, PoolConfig:{}", host, port, timeout, poolConfig);
    return new JedisPool(poolConfig, host, port, timeout, password);
}

Solution

  • I fixed the issue by changing the bean to use RedisProperties. Here is the code that ended up working.

    @Bean
    public JedisPool getJedisPool(RedisProperties redisProperties) {
        Pool jedisProperties = redisProperties.getJedis().getPool();
        String password = StringUtils.isEmpty(redisProperties.getPassword()) ? null : redisProperties.getPassword();
        int timeout = (int) redisProperties.getTimeout().toMillis();
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(jedisProperties.getMaxIdle());
        poolConfig.setMaxTotal(jedisProperties.getMaxActive() + jedisProperties.getMaxIdle());
        poolConfig.setMinIdle(jedisProperties.getMinIdle());
        log.info("Starting Redis with Host:{}, Port:{}, Timeout(ms):{}, PoolConfig:{}", redisProperties.getHost(), redisProperties.getPort(),
                timeout, poolConfig);
        return new JedisPool(poolConfig, redisProperties.getHost(), redisProperties.getPort(), timeout, password);
    }
    

    I am not very sure if this is the correct way to configure Jedis on SpringBoot 2.0. In any case, this works.