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

猜你喜欢

转载自mmblue.iteye.com/blog/2019442