static void Main(string[] args) { var client = new org.apache.zookeeper.ZooKeeper( "10.217.9.184:2181,10.217.6.124:2181,10.217.6.140:2181,10.217.6.222:2181,10.217.9.47:2181", 5000, null); Thread.Sleep(1000); var path = "/LinuxMustDie"; var data = "LINUX IS ALIVE!!"; var createResult = client.createAsync(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); Console.WriteLine($"Create result = {createResult}"); var setDataResult = client.setDataAsync(path, Encoding.UTF8.GetBytes(data)).GetAwaiter().GetResult(); Console.WriteLine($"SetData result version = {setDataResult.getVersion()}"); var getDataResult = client.getDataAsync(path).GetAwaiter().GetResult(); Console.WriteLine($"GetData result = {Encoding.UTF8.GetString(getDataResult.Data)}"); Console.ReadKey(); client.deleteAsync(path).Wait(); }
public async Task <bool> ReleaseLock(string key) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } var sta = await _zooKeeper.existsAsync($"/PessimisticLock/{key}", new WatcherSample()); if (sta == null) { return(true); } var lockData = await _zooKeeper.getDataAsync($"/PessimisticLock/{key}", new WatcherSample()); var mark = Encoding.UTF8.GetString(lockData.Data) == key; if (mark) { await _zooKeeper.deleteAsync($"/PessimisticLock/{key}", sta.getVersion()); } return(true); }
public override async Task process(WatchedEvent @event) { var path = @event.getPath(); Debug.WriteLine($"ZK event {@event.get_Type()} on {path}"); if (@event.get_Type() == Event.EventType.NodeDeleted) { onChange(path, null); } if (@event.get_Type() == Event.EventType.NodeDataChanged || @event.get_Type() == Event.EventType.NodeCreated) { try { var data = await zooKeeper.getDataAsync(path, this); onChange(path, Encoding.UTF8.GetString(data.Data)); } catch (KeeperException.NoNodeException) { onChange(path, null); } } }
private async Task SetupKey(string featureKey) { var path = GetPathForKey(featureKey); /* await TryAndRetry(async z => * { * var doLoop = false; * do * { */ try { var res = await zooKeeper.getDataAsync(path, watcher); OnZookeeperEntryChanged(path, res.Data == null ? null : Encoding.UTF8.GetString(res.Data)); } catch (KeeperException.NoNodeException) { // setup watcher to catch node creation if (await zooKeeper.existsAsync(path, watcher) == null) { OnZookeeperEntryChanged(path, null); } // else // doLoop = true; // if entry created in between } /* * } while (doLoop); * * });*/ }
public async Task <int> IncrementAndWatchEpochAsync(int currentEpoch, Watcher watcher) { var actionToPerform = "increment epoch"; while (true) { await BlockUntilConnected(actionToPerform); try { var data = System.Text.Encoding.UTF8.GetBytes("0"); var stat = await zookeeper.setDataAsync(this.epochPath, data, currentEpoch); var dataRes = await zookeeper.getDataAsync(this.epochPath, watcher); if (dataRes.Stat.getVersion() == stat.getVersion()) { return(dataRes.Stat.getVersion()); } else { throw new ZkStaleVersionException("Between incrementing the epoch and setting a watch the epoch was incremented"); } } catch (KeeperException.BadVersionException e) { throw new ZkStaleVersionException($"Could not {actionToPerform} as the current epoch was incremented already.", e); } catch (KeeperException.NoNodeException e) { throw new ZkInvalidOperationException($"Could not {actionToPerform} as the node does not exist.", e); } catch (KeeperException.ConnectionLossException) { // do nothing, the next iteration will try again } catch (KeeperException.SessionExpiredException e) { throw new ZkSessionExpiredException($"Could not {actionToPerform} as the session has expired: ", e); } catch (Exception e) { throw new ZkInvalidOperationException($"Could not {actionToPerform} due to an unexpected error", e); } } }
protected static void EnsureDataExists(string path, org.apache.zookeeper.ZooKeeper client, string expectedData, int expectedVersion = 0) { var expectedDataBytes = Encoding.UTF8.GetBytes(expectedData); var getDataResult = client.getDataAsync(path).GetAwaiter().GetResult(); getDataResult.Data.Should().BeEquivalentTo(expectedDataBytes); //getDataResult.EnsureSuccess(); //getDataResult.Path.Should().Be(path); //getDataResult.Status.Should().Be(ZooKeeperStatus.Ok); //getDataResult.Payload.Item1.Should().BeEquivalentTo(expectedDataBytes); //getDataResult.Payload.Item2.Version.Should().Be(expectedVersion); }
public async Task <IActionResult> List() { var list = new List <Connection>(); var connResult = await _zooKeeper.getChildrenAsync("/connections"); foreach (var conn in connResult.Children) { var connData = await _zooKeeper.getDataAsync($"/connections/{conn}/value"); var connStr = Encoding.UTF8.GetString(connData.Data); var item = new Connection { Id = conn, Value = connStr }; list.Add(item); } return(Ok(list)); }
public async Task RefreshAsync() { var connDic = new Dictionary <string, string>(); var isExisted = await _zooKeeper.existsAsync("/connections"); if (isExisted == null) { await _zooKeeper.createAsync("/connections", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } var connResult = await _zooKeeper.getChildrenAsync("/connections", new ConnectionWatcher(this)); foreach (var conn in connResult.Children) { var connData = await _zooKeeper.getDataAsync($"/connections/{conn}/value"); var connStr = Encoding.UTF8.GetString(connData.Data); connDic[conn] = connStr; } _cache.Set("connections", connDic); }
public async Task <DataResult> GetDataAsync(string path, bool watch) { return(await _zooKeeper.getDataAsync(path, watch)); }
/// <summary> /// 获取锁 /// </summary> /// <param name="millisecondsTimeout">等待时间</param> /// <returns></returns> public async Task <bool> TryLock(int millisecondsTimeout = 0) { try { zooKeeper = new org.apache.zookeeper.ZooKeeper("127.0.0.1", 50000, new MyWatcher()); //创建锁节点 if (await zooKeeper.existsAsync("/Locks") == null) { await zooKeeper.createAsync("/Locks", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } //新建一个临时锁节点 lockNode = await zooKeeper.createAsync("/Locks/Lock_", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); //获取锁下所有节点 var lockNodes = await zooKeeper.getChildrenAsync("/Locks"); lockNodes.Children.Sort(); //判断如果创建的节点就是最小节点 返回锁 if (lockNode.Split("/").Last() == lockNodes.Children[0]) { return(true); } else { //当前节点的位置 var location = lockNodes.Children.FindIndex(n => n == lockNode.Split("/").Last()); //获取当前节点 前面一个节点的路径 var frontNodePath = lockNodes.Children[location - 1]; //在前面一个节点上加上Watcher ,当前面那个节点删除时,会触发Process方法 await zooKeeper.getDataAsync("/Locks/" + frontNodePath, myWatcher); //如果时间为0 一直等待下去 if (millisecondsTimeout == 0) { myWatcher.AutoResetEvent.WaitOne(); } else //如果时间不为0 等待指定时间后,返回结果 { var result = myWatcher.AutoResetEvent.WaitOne(millisecondsTimeout); if (result)//如果返回True,说明在指定时间内,前面的节点释放了锁(但是) { //获取锁下所有节点 lockNodes = await zooKeeper.getChildrenAsync("/Locks"); //判断如果创建的节点就是最小节点 返回锁 if (lockNode.Split("/").Last() == lockNodes.Children[0]) { return(true); } else { return(false); } } else { return(false); } } } } catch (KeeperException e) { await UnLock(); throw e; } return(false); }