版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vtopqx/article/details/82557374
有关Redis Sentinel的具体配置,在前面的文章中已经有,
可以参考:https://blog.csdn.net/vtopqx/article/details/49247285
Redis Sentinel配置完成后,有的需要在Java中连接,其中有好些人问过我相关代码,
所以特地去磁盘找了下以前写的demo例子代码,这里写上来备注一下,有需要的可以参考,
不多说,很简单的实现,直接上代码:
package com;
import java.util.HashSet;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
/**
* @ClassName: JRedisSentinelTest
* @Description: Redis-使用Sentine进行测试(主要测试单机监控[master-slave]替换与客户端关系)
* @author sam
* @date 2015-6-1 上午9:21:37
* @version V1.0
*/
public class JRedisSentinelTest {
public static void main(String[] args) {
//服务IP
String ip = "172.168.x.y";
Set sentinels = new HashSet();
//Sentine端口
sentinels.add(new HostAndPort(ip, 26379).toString());
sentinels.add(new HostAndPort(ip, 26380).toString());
JedisSentinelPool sentinelPool = new JedisSentinelPool("master1", sentinels);
System.out.println("Current master: " + sentinelPool.getCurrentHostMaster().toString());
Jedis master = sentinelPool.getResource();
master.set("username","liangzhichao");
sentinelPool.returnResource(master);
Jedis master2 = sentinelPool.getResource();
String value = master2.get("username");
System.out.println("username: " + value);
master2.close();
sentinelPool.destroy();
}
}
以上Sentine连接需要 jedis-2.6.1.jar,其他版本也可以,由于这个代码是几年前写的了,所以当时用的是2.6,现在都是3.x了。