zookeeper session过期 Curator

zookeeper 中 session 过期解释:

 

当client 和 server 连接后,不是100%保证一直可以连上的。比如网络问题。那么client需要重连,这种机制自己实现比较复杂,还在有Curator客户端帮我们解决了,只需要在连接后注册一个监听器就可以了。

模拟服务端线路不通可以开启防火墙方法,或者,

开启81端口:
iptables -I INPUT -i eth0 -p tcp --dport 81 -j ACCEPT
iptables  -I OUTPUT -o eth0 -p tcp --sport 81 -j ACCEPT

关闭81端口:
iptables -I INPUT -i eth0 -p tcp --dport 81 -j DROP
iptables -I OUTPUT -o eth0 -p tcp --sport 81 -j DROP

然后保存

具体代码如下: 

代码如下:

String path = "/session/service-";
		SessionConnectionStateListener listener = new SessionConnectionStateListener(path,zookeeperConnectionString);
		client.getConnectionStateListenable().addListener(listener);
		client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
		.forPath(path,"haha".getBytes());

 

下面是监听器:

package com.mmblue.demo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.zookeeper.CreateMode;

public class SessionConnectionStateListener implements ConnectionStateListener {
	private String zkRegPathPrefix;
	private String regContent;

	public SessionConnectionStateListener(String zkRegPathPrefix, String regContent) {
		this.zkRegPathPrefix = zkRegPathPrefix;
		this.regContent = regContent;
	}

	@Override
	public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState){
		if(connectionState == ConnectionState.LOST){
			while(true){
				try {
					System.err.println("我来了,嘿嘿");
					if(curatorFramework.getZookeeperClient().blockUntilConnectedOrTimedOut()){
						curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(zkRegPathPrefix, regContent.getBytes("UTF-8"));
						break;
					}
				} catch (InterruptedException e) {
					break;
				} catch (Exception e){
					
				}
			}
		}
	}	
}

 

参考文章:

http://www.codelast.com/?p=6049

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值