示例代码
package com.example.redis.client.cluster;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.Set;
public class JedisClusterMain {
public static void main(String[] args) {
JedisPoolConfig config = new JedisPoolConfig();
Set<HostAndPort> nodeList = new HashSet<>();
nodeList.add(new HostAndPort("127.0.0.1", 7000));
nodeList.add(new HostAndPort("127.0.0.1", 7001));
nodeList.add(new HostAndPort("127.0.0.1", 7002));
nodeList.add(new HostAndPort("127.0.0.1", 7003));
nodeList.add(new HostAndPort("127.0.0.1", 7004));
nodeList.add(new HostAndPort("127.0.0.1", 7005));
JedisCluster jedisCluster = new JedisCluster(nodeList, 3000, config);
jedisCluster.set("James", "Bond");
String value = jedisCluster.get("James");
System.out.println(value);
}
}
使用技巧
- 作为单例使用,因为其中内置了所有节点的连接池;
- 无需手动借还连接;
- 合理设置 commons-pool 配置;