在Spring启动2上配置Jedis

时间:2018-04-07 23:20:09

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

我正在尝试从spring boot 1.5.5迁移到spring boot 2.我为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

我正在尝试使用Jedis配置而不是生菜。我按照文档中的建议导入spring-starter-redis-data时忽略了生菜模块。

以下是尝试初始化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);
}

1 个答案:

答案 0 :(得分:0)

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.