Redis 集群连接池的java初始化

集群配置方式

java 代码

@Bean
public JedisCluster getRedisCluster() {
    String nodes = environment.getProperty("redis.cluster.nodes");
    int maxTotal = environment.getProperty("redis.config.maxTotal", Integer.class);
    int maxIdle = environment.getProperty("redis.config.maxIdle", Integer.class);
    int maxRedirections = environment.getProperty("redis.config.maxRedirections", Integer.class);
    int timeout = environment.getProperty("redis.config.timeout", Integer.class);
    boolean testOnBorrow = environment.getProperty("redis.config.testOnBorrow", Boolean.class);
    Set<HostAndPort> clusterNodes = new HashSet<HostAndPort>();
    if (nodes != null && !nodes.trim().equals("")) {
      String[] nodesArray = nodes.split(",");
      for (String node : nodesArray) {
        try {
          String[] host = node.split(":");
          String ip = host[0];
          int port = Integer.valueOf(host[1]);
          clusterNodes.add(new HostAndPort(ip, port));
        } catch (Exception ex) {
          continue;
        }
      }
    }
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(maxTotal);
    config.setMaxIdle(maxIdle);
    config.setTestOnBorrow(testOnBorrow);
    config.setMaxWaitMillis(10000);
    return new JedisCluster(clusterNodes, timeout, maxRedirections, config);
  }

配置信息

redis.cluster.nodes=127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002
redis.config.maxTotal=1000
redis.config.maxIdle=500
redis.config.maxRedirections=1000
redis.config.timeout=2000
redis.config.testOnBorrow=true

单机配置方式

java 代码

  @Bean
  public ShardedJedisPool getShardedJedisPool() {
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    jedisPoolConfig.setMaxTotal(env.getProperty("redis.config.maxTotal", Integer.class));
    jedisPoolConfig.setMaxIdle(env.getProperty("redis.config.maxIdle", Integer.class));
    jedisPoolConfig.setMaxWaitMillis(env.getProperty("redis.config.maxWaitMillis", Long.class));
    jedisPoolConfig.setTestOnBorrow(env.getProperty("redis.config.testOnBorrow", Boolean.class));
    List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>();
    jedisShardInfoList.add(new JedisShardInfo(env.getProperty("redis.ip"),env.getProperty("redis.port", Integer.class)));
    return new ShardedJedisPool(jedisPoolConfig, jedisShardInfoList);
  }

配置信息

redis.config.maxTotal=1000
redis.config.maxIdle=500
redis.config.maxWaitMillis=10000
redis.config.testOnBorrow=true
redis.ip=123.57.3.116
redis.port=6379