在上一节我介绍了如何搭建redis哨兵模式,那么这一节我接着介绍使用jedis来连接操作哨兵模式下的redis。连接redis不是直接连接的master的ip,而是来连接的哨兵们,把哨兵ip放在set集合中作为参数来创建连接池,内部会获取到当前master。
@Test
public void testSentinel() {
String masterName = "mymaster";
String password = "";
// 设置参数
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(10);
jedisPoolConfig.setMaxIdle(5);
jedisPoolConfig.setMinIdle(5);
// 哨兵信息,注意填写哨兵的地址
Set<String> sentinels = new HashSet<String>();
sentinels.add("118.190.156.123:26379");
sentinels.add("118.190.156.123:26380");
sentinels.add("118.190.156.123:26381");
// 创建连接池
JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinels, jedisPoolConfig);
//JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinels,jedisPoolConfig, password);
// 获取客户端
Jedis jedis = pool.getResource();
// 执行两个命令
jedis.set("name", "sentinel-name");
String value = jedis.get("name");
System.out.println(value);
}
在实践过程中对配置文件中的bind有了新的认识,我这里是把bind设为0.0.0.0,表示任何机器都可以连接redis服务器。