import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import java.util.HashSet;

@SpringBootConfiguration
public class RedisConfig {

    private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Value("${redis.maxIdle}")
    private Integer maxIdle;
    @Value("${redis.maxTotal}")
    private Integer maxTotal;
    @Value("${redis.host}")
    private String host;
    @Value("${redis.password}")
    private String password;
    @Value("${redis.port}")
    private Integer port;

    @Value("${redis.sentinels.set}")
    private HashSet<String> sentinels;
    @Value("${redis.sentinels.master}")
    private String sentinelsMaster;
    @Value("${redis.sentinels.password}")
    private String sentinelsPassword;

    public JedisPoolConfig jedisPoolConfig(){    //这个是修改redis性能的时候需要的对象
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setTestOnBorrow(true);

        return jedisPoolConfig;
    }

    @Bean
    @ConditionalOnProperty(value = "redis.sentinel.enable", havingValue = "false", matchIfMissing = true)
    public JedisPool jedisPool(){
        logger.info("加载JedisPool");
        JedisPoolConfig jedisPoolConfig = jedisPoolConfig();
        return new JedisPool(jedisPoolConfig, host, port, 10000, password);
    }

    @Bean
    @ConditionalOnProperty(value = "redis.sentinel.enable", havingValue = "true", matchIfMissing = false)
    public JedisSentinelPool jedisSentinelPool() {
        logger.info("加载JedisSentinelPool");
        JedisPoolConfig config = jedisPoolConfig();
        JedisSentinelPool jedisPool = new JedisSentinelPool(sentinelsMaster, sentinels, config, 10000, sentinelsPassword);
        return jedisPool;
    }
}


JedisUtils 加入这段以选择所用的连接池


public class JedisUtils {
	private static Logger logger = LoggerFactory.getLogger(JedisUtils.class);
	private static Pool jedisPool =  null;
	static {
		try {
			jedisPool = SpringContextHolder.getBean(JedisSentinelPool.class);
		} catch (Exception e) {
			logger.warn("切换为JedisPool");
			jedisPool = SpringContextHolder.getBean(JedisPool.class);
		}
	}
}


配置

# false:直连单机 true:连接哨兵
redis.sentinel.enable=true

redis.sentinels.set=127.0.0.1:6390,127.0.0.1:6391,127.0.0.1:6392
redis.sentinels.master=bbq
redis.sentinels.password=123456

redis.host=127.0.0.1
redis.password=123456
redis.port=6379

#最大连接数
redis.maxTotal=60000
#最大空闲连接
redis.maxIdle=300
#最小空闲连接
redis.minIdle=5

最后

只需修改redis.sentinel.enable配置值就可以切换项目连接池。

11-11 10:35