zookeeper session过期该如何理解

发布时间:2021-12-17 16:27:14 作者:柒染
来源:亿速云 阅读:250

zookeeper session过期该如何理解,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

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){
					
				}
			}
		}
	}	
}

关于zookeeper session过期该如何理解问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. Zookeeper详解(二):Zookeeper安装和运行
  2. Zookeeper理解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

zookeeper session

上一篇:virtual interface怎么使用

下一篇:如何进行springboot配置templates直接访问的实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》