Java通过JedisSentinelPool连接Redis,master切换无影响。

网上搜了很久,发现很多 Redis高可用的方案,发现这种是最符合我的情况的。master.disconnect();用于清理链接。

希望对你有所帮助。

Java通过JedisSentinelPool连接Redis,实现插入时master的切换无影响。

import java.util.HashSet;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
public class JRedisSentinelTest {
public static void main(String[] args) throws InterruptedException {
    //服务IP
    String ip = "xx.xx.xx.xx";
    int TimeOut = 10000;
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(200);
    config.setMaxIdle(50);
  //在获取连接的时候检查有效性, 
  //config.setTestOnBorrow(true);
  //在空闲时检查有效性, 默认false
  //config.setTestWhileIdle(true);
    config.setMaxWaitMillis(1000);
    String masterName = "mymaster";
    String password = "123456";
    
    Set sentinels = new HashSet();
    //Sentine端口
    sentinels.add(new HostAndPort(ip, 26371).toString());
    sentinels.add(new HostAndPort(ip, 26372).toString());
    sentinels.add(new HostAndPort(ip, 26373).toString());
    JedisSentinelPool sentinelPool = new JedisSentinelPool(masterName, sentinels, config, TimeOut,password);
    System.out.println("Current master: " + sentinelPool.getCurrentHostMaster().toString());
    for(int i=0;i<1000;i++) {
        Jedis master = sentinelPool.getResource();
        master.set(""+i,""+i);
        System.out.println("第"+i+"次沉睡");
        master.close();
        master.disconnect();
        Thread.sleep(5000);
    }
    sentinelPool.destroy();
}

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值