/// <summary> /// 初始化客户端连接 /// </summary> public void InitConnect() { try { //Zookeeper连接字符串,采用host:port格式,多个地址之间使用逗号(,)隔开 //string connectionString = "192.168.209.133:2181,192.168.209.133:2181,192.168.209.133:2181"; string connectionString = "192.168.10.53:2181"; //会话超时时间,单位毫秒 int sessionTimeOut = 10000; //异步监听 var watcher = new MyWatcher("ConnectWatcher"); //连接 this.zooKeeper = new ZooKeeper(connectionString, sessionTimeOut, watcher); Thread.Sleep(1000);//停一秒,等待连接完成 while (zooKeeper.getState() == ZooKeeper.States.CONNECTING) { Console.WriteLine("等待连接完成..."); Thread.Sleep(1000); } var state = zooKeeper.getState(); if (state != ZooKeeper.States.CONNECTED && state != ZooKeeper.States.CONNECTEDREADONLY) { Console.WriteLine("连接失败:" + state); return; } } catch (Exception ex) { Console.WriteLine("连接失败:" + ex.Message); } }
/// <summary> /// Initialize cloud state /// </summary> public async Task InitAsync() { if (isInitialized) { return; } await semaphoreSlim.WaitAsync().ConfigureAwait(false); try { if (!isInitialized) { await UpdateAsync().ConfigureAwait(false); if (zooKeeper.getState() != ZooKeeper.States.CONNECTED && zooKeeper.getState() != ZooKeeper.States.CONNECTEDREADONLY) { throw new Exceptions.SolrNetCloudConnectionException($"Cannot connect to the Zookeeper instance {zooKeeperConnection}. Current state: {zooKeeper.getState()} "); } isInitialized = true; } } finally { semaphoreSlim.Release(); } }
public async Task ConnectAsync() { var times = 0; if (OnWatch == null) { OnWatch += ZkConnection_OnWatch; } _zk = new ZooKeeper(_options.ConnectionString, _options.SessionTimeout, new InternalZkWatchWrapper(OnWatch)); _logger.LogInformation("Connecting to zookeeper..."); while (_zk.getState() == ZooKeeper.States.CONNECTING) { await Task.Delay(100); times++; if (times == 100) { throw new ZkException("Connection timed out."); } } var state = _zk.getState(); if (state != ZooKeeper.States.CONNECTED && state != ZooKeeper.States.CONNECTEDREADONLY) { throw new ZkException($"Connect failed, state: {state}"); } _logger.LogInformation($"Zookeeper connected successfully, state: {state}"); _connected = true; }
/// <summary> /// 返回null表示连接不成功 /// </summary> /// <param name="authEnum"></param> /// <param name="authInfo"></param> /// <returns></returns> public ZooKeeper Connect(AuthEnum authEnum, string authInfo) { foreach (string address in _address) { _zooKeeper = new ZooKeeper(address, _sessiontTimeout, new DefaultWatcher()); if (authEnum != AuthEnum.world) { _zooKeeper.addAuthInfo(authEnum.ToString(), System.Text.Encoding.UTF8.GetBytes(authInfo)); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (stopwatch.ElapsedMilliseconds < _connectTimeout / _address.Count) { ZooKeeper.States states = _zooKeeper.getState(); if (states == ZooKeeper.States.CONNECTED || states == ZooKeeper.States.CONNECTEDREADONLY) { break; } } stopwatch.Stop(); if (_zooKeeper.getState().ToString().ToUpper().Contains("CONNECTED")) { break; } } return(_zooKeeper); }
private void Conn(ZookeeperOptions zookeeperOptions) { bool isReadOnly = default(Boolean); Wathcer = new WaitConnWatch(autoResetEvent[0], _logger); if (isReadOnly != zookeeperOptions.IsReadOnly) { isReadOnly = zookeeperOptions.IsReadOnly; } byte[] pwd = new byte[0]; //如果没有密码和sessionId if (string.IsNullOrEmpty(zookeeperOptions.SessionPwd) && _zookeeperOptions.SessionId == default(int)) { _zookeeper = new ZooKeeper(zookeeperOptions.Connectstring, zookeeperOptions.SessionTimeout, Wathcer, isReadOnly); } else if (!string.IsNullOrEmpty(zookeeperOptions.SessionPwd)) { pwd = System.Text.Encoding.Default.GetBytes(zookeeperOptions.SessionPwd); _zookeeper = new ZooKeeper(zookeeperOptions.Connectstring, zookeeperOptions.SessionTimeout, Wathcer, 0, pwd, isReadOnly); } else { _zookeeper = new ZooKeeper(zookeeperOptions.Connectstring , zookeeperOptions.SessionTimeout, Wathcer, zookeeperOptions.SessionId, pwd, isReadOnly); } if (_zookeeper.getState() == States.CONNECTING) { _logger.LogDebug("当前状态:CONNECTING。阻塞等待"); autoResetEvent[0].WaitOne(); } }
public static bool needReConnection(Exception e) { return //(e is KeeperException.SessionExpiredException) //|| (e is KeeperException.AuthFailedException) || (e is KeeperException.ConnectionLossException) || (currentZookeeper.getState() != ZooKeeper.States.CONNECTED && currentZookeeper.getState() != ZooKeeper.States.CONNECTEDREADONLY); }
public static ZooKeeper GetClient() { if (!(Client.getState() == ZooKeeper.States.CONNECTED || Client.getState() == ZooKeeper.States.CONNECTEDREADONLY)) { Client = CreateClient(_option); } return(Client); }
/// <summary> /// 得到连接状态 /// </summary> /// <returns></returns> public string GetState() { if (_zooKeeper != null) { ZooKeeper.States states = _zooKeeper.getState(); return(states.ToString()); } return(_fail); }
//得到node下所有注册的服务节点列表,连接异常的话重试4回 private ChildrenResult GetChild(ref ZooKeeper zk, string node, Watcher watcher, int runcnt = 0) { if (zk == null) { zk = createClientForCall(watcher); } ChildrenResult children; try { var state = zk.getState(); if (state != ZooKeeper.States.CONNECTED) { zk = createClientForCall(watcher); } children = zk.getChildrenAsync(node, true).Result; } catch (AggregateException ex) { if (runcnt <= 4) //4次机会重发,每次等待2*失败次数的时间 { runcnt++; Thread.Sleep(1500 * runcnt); children = GetChild(ref zk, node, watcher, runcnt); } else { children = null; } } return(children); }
/// <summary> /// 得到连接状态 /// </summary> /// <returns></returns> public string GetState() { try { if (_zooKeeper != null) { ZooKeeper.States states = _zooKeeper.getState(); return(states.ToString()); } } catch (Exception ex) { _log.ErrorFormat("获取zookeeper连接状态发生异常:{0}", ex.Message + ex.StackTrace); } return(_fail); }
public void KillSession(TimeSpan timeout) { if (!IsConnected) { return; } var connectionString = Curator.getZookeeperClient().getCurrentConnectionString(); var zooKeeper = new ZooKeeper(connectionString, 5000, null, SessionId, SessionPassword); try { var watch = Stopwatch.StartNew(); while (watch.Elapsed < timeout) { if (zooKeeper.getState().Equals(ZooKeeper.States.CONNECTED)) { return; } Thread.Sleep(100); } throw new TimeoutException($"Expected to kill session within {timeout}, but failed to do so."); } finally { zooKeeper.close(); } }
public async Task <ZooKeeper> Get(String connStr) { ZooKeeper zk = null; bool isExists = MappedZooKeepers.ContainsKey(connStr); if (isExists) { zk = MappedZooKeepers[connStr]; var zkState = zk.getState(); if (zkState == ZooKeeper.States.CLOSED || zkState == ZooKeeper.States.NOT_CONNECTED ) { await Remove(connStr); zk = new ZooKeeper(connStr, sessionTimeout, NoneWatcher.Instance); MappedZooKeepers.Add(connStr, zk); } return(zk); } zk = new ZooKeeper(connStr, sessionTimeout, NoneWatcher.Instance); MappedZooKeepers.Add(connStr, zk); return(zk); }
private bool Regedit() { if (_zk == null) { _zk = new ZooKeeper(_service.ZookeeperConfig.Host, _service.ZookeeperConfig.SessionTimeout, this); int count = 0; while (_zk.getState() != ZooKeeper.States.CONNECTED) { if (count++ > 50) { throw new Exception("ZooKeeper 连接失败"); } System.Threading.Thread.Sleep(100); } } var zNode = $"{_service.ZookeeperConfig.NodeParent}/{_host}:{_service.Port}-{_service.Weight}"; if (!CheckNodeParent()) { return(false); } if (!RegeditNode(zNode, 0)) { return(false); } return(true); }
private bool IsAlive() { if (instance != null) { var zkState = instance.getState(); bool isAlive = (zkState != ZooKeeper.States.CLOSED && zkState != ZooKeeper.States.AUTH_FAILED); logger.LogDebug($"ZooKeeper.States is not OK!"); return(isAlive); } return(false); }
private ZooKeeper CreateZk() { var zk = new ZooKeeper(Option.ConnectionString, Option.SessionTimeout, new ZkWatcher(_changeEvent, this), Option.SessionId, Option.SessionPasswd, Option.ReadOnly); int currentTryCount = 0; while (zk.getState() != ZooKeeper.States.CONNECTED && currentTryCount < Option.RetryCount) { Thread.Sleep(1000); } return(zk); }
private static void connection(string connectionString, int sessionTimeout, Watcher watcher, Action reConnectionAction = null) { if (currentZookeeper?.getState() != ZooKeeper.States.CONNECTED && !isConnectioning) { lock (rootLock) { if (currentZookeeper?.getState() != ZooKeeper.States.CONNECTED && !isConnectioning) { isConnectioning = true; gotoLable: logger.LogInformation($"开始初始化ZK连接:{connectionString}"); try { ConnectionString = connectionString; currentZookeeper = new ZooKeeper(connectionString, sessionTimeout, watcher); var state = currentZookeeper.getState(); while (true) { if (state == ZooKeeper.States.CONNECTED) { isConnectioning = false; reConnectionAction?.Invoke(); logger.LogInformation($"ZK连接成功:{connectionString}"); break; } Thread.Sleep(500); state = currentZookeeper.getState(); } } catch (Exception ex) { Thread.Sleep(1000); logger.LogError(ex, $"zk连接异常"); goto gotoLable; // 一直尝试连接 } } } } }
/// <summary> /// 建立ZK连接 返回null表示连接不成功 /// </summary> /// <param name="authEnum"></param> /// <param name="authInfo"></param> /// <returns></returns> public ZooKeeper Connect(AuthEnum authEnum, string authInfo) { try { foreach (string address in _address) { _zooKeeper = new ZooKeeper(address, _sessiontTimeout, new NodeWatcher(_log)); if (authEnum != AuthEnum.world) { _zooKeeper.addAuthInfo(authEnum.ToString(), System.Text.Encoding.UTF8.GetBytes(authInfo)); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (stopwatch.ElapsedMilliseconds < _connectTimeout / _address.Count) { ZooKeeper.States states = _zooKeeper.getState(); if (states == ZooKeeper.States.CONNECTED || states == ZooKeeper.States.CONNECTEDREADONLY) { break; } } stopwatch.Stop(); if (_zooKeeper.getState().ToString().ToUpper().Contains("CONNECTED")) { break; } } return(_zooKeeper); } catch (Exception ex) { _log.ErrorFormat("连接zookeeper发生异常:{0}", ex.Message + ex.StackTrace); } return(null); }
private bool SetServerConfig(Config.Service service) { try { if (_zk == null) { _zk = new ZooKeeper(service.ZookeeperConfig.Host, service.ZookeeperConfig.SessionTimeout, this); int count = 0; while (_zk.getState() != ZooKeeper.States.CONNECTED) { if (count++ > 50) { throw new Exception("ZooKeeper 连接失败"); } System.Threading.Thread.Sleep(100); } } _defaultHost = service.Host; var children = _zk.getChildrenAsync(service.ZookeeperConfig.NodeParent, this).Result.Children; if (children != null && children.Count > 0) { service.Host = string.Join(",", children); } if (!_firstGetConfig) //首次连接,不需要执行更新方法。 { if (_updateHostDelegate != null) { _updateHostDelegate(); } } return(true); } catch (Exception ex) { ThriftLog.Error(ex.Message + ex.StackTrace); return(false); } }
private async Task <bool> InternalLockLoopAsync(long startMillis, int millisToWait, string ourPath) { var haveTheLock = false; var doDelete = false; try { while (_zkClient.getState() == ZooKeeper.States.CONNECTED) { // 获取排序的子节点 var children = await GetSortedChildren(); //var sequenceNodeName = ourPath.Substring(_basePath.Length + 1); // 判断能否持有锁 var predicateResults = _driver.GetTheLock(_zkClient, children, ourPath, _maxLeases); // 已获取到锁 if (predicateResults.Locked) { return(true); } // 上一个节点路径 var previousSequencePath = ZKPaths.MakePath(_basePath, predicateResults.NodeToWatch); try { // 剩余等待时间 millisToWait -= (int)(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - startMillis); startMillis = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); if (millisToWait <= 0) { // 超时,删除创建的节点 doDelete = true; break; } // 设置释放锁监听 await _zkClient.getDataAsync(previousSequencePath, _watcher); // 阻塞 等待锁释放或超时 if (!await _signal.WaitAsync(millisToWait)) { doDelete = true; break; } } catch (KeeperException.NoNodeException ex) { // 上一个节点已被删除(即释放锁)。再次尝试获取 } } } catch (Exception ex) { doDelete = true; throw ex; } finally { if (doDelete) { await DeleteOurPathAsync(ourPath); } } return(haveTheLock); }
static void Sqmple() { //Zookeeper连接字符串,采用host:port格式,多个地址之间使用逗号(,)隔开 string connectionString = "127.0.0.1:2181"; //会话超时时间,单位毫秒 int sessionTimeOut = 10000; //异步监听 var watcher = new MyWatcher("ConnectWatcher"); //连接 ZooKeeper zooKeeper = new ZooKeeper(connectionString, sessionTimeOut, watcher); Thread.Sleep(1000);//停一秒,等待连接完成 while (zooKeeper.getState() == ZooKeeper.States.CONNECTING) { Console.WriteLine("等待连接完成..."); Thread.Sleep(1000); } var state = zooKeeper.getState(); if (state != ZooKeeper.States.CONNECTED && state != ZooKeeper.States.CONNECTEDREADONLY) { Console.WriteLine("连接失败:" + state); Console.ReadKey(); return; } //创建znode节点 { var data = Encoding.UTF8.GetBytes("hello world"); List <ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;//创建节点时的acl权限,也可以使用下面的自定义权限 //List<ACL> acl = new List<ACL>() { // new ACL((int)ZooDefs.Perms.READ, new Id("ip", "127.0.0.1")), // new ACL((int)(ZooDefs.Perms.READ | ZooDefs.Perms.WRITE), new Id("auth", "id:pass")) //}; CreateMode createMode = CreateMode.PERSISTENT; zooKeeper.createAsync("/mynode", data, acl, createMode).Wait(); Console.WriteLine("完成创建节点"); } //节点是否存在 { var exists = zooKeeper.existsAsync("/mynode", new MyWatcher("ExistsWatcher")).GetAwaiter().GetResult(); Console.WriteLine("节点是否存在:" + exists); } //获取节点数据 { var dataResult = zooKeeper.getDataAsync("/mynode", new MyWatcher("GetWatcher")).GetAwaiter().GetResult(); var value = Encoding.UTF8.GetString(dataResult.Data); Console.WriteLine("完成读取节点:" + value); } //设置节点数据 { var data = Encoding.UTF8.GetBytes("hello world again"); zooKeeper.setDataAsync("/mynode", data); Console.WriteLine("设置节点数据"); } //重新获取节点数据 { var dataResult = zooKeeper.getDataAsync("/mynode", new MyWatcher("GetWatcher")).GetAwaiter().GetResult(); var value = Encoding.UTF8.GetString(dataResult.Data); Console.WriteLine("重新获取节点数据:" + value); } //移除节点 { zooKeeper.deleteAsync("/mynode").Wait(); Console.WriteLine("移除节点"); } Console.WriteLine("完成"); Console.ReadKey(); }