private async Task CreateSubdirectory(IZookeeperClient zooKeeperClient, string path) { if (await zooKeeperClient.ExistsAsync(path)) { return; } if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation($"节点{path}不存在,将进行创建。"); } var childrens = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var nodePath = "/"; foreach (var children in childrens) { nodePath += children; if (!await zooKeeperClient.ExistsAsync(nodePath)) { await zooKeeperClient.CreateAsync(nodePath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } nodePath += "/"; } }
private void CreateNode(string node) { if (!_client.ExistsAsync(node).GetAwaiter().GetResult()) { _client.CreateAsync(node, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).GetAwaiter().GetResult(); } }
private IList <ServicePublishInfo> GetServicePublishInfos(int serviceId) { var path = GetServicePath(serviceId); if (!client.ExistsAsync(path).Result) { logger.LogDebug($"Service not found on zookeeper. ServiceId={serviceId}"); throw new Exception($"Service not found on zookeeper. ServiceId={serviceId}"); } var hosts = client.GetChildrenAsync(path).Result.ToList(); if (hosts.Count == 0) { logger.LogDebug($"No host config on zookeeper. ServiceId={serviceId}"); throw new Exception($"No host config on zookeeper. ServiceId={serviceId}"); } var list = new List <ServicePublishInfo>(); foreach (var hostName in hosts) { var info = GetServicePublishInfo($"{path}/{hostName}"); list.Add(info); } return(list); }
public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) { var existPath = await _client.ExistsAsync(ListenerPath); if (!existPath) { await _client.CreateRecursiveAsync(ListenerPath, Encoding.UTF8.GetBytes("Bucket.Listener")); } await _client.SubscribeDataChange(ListenerPath, async (ct, args) => { if (!_isSubscribe) { return; } var currentData = Encoding.UTF8.GetString(args.CurrentData.ToArray()); if (!string.IsNullOrWhiteSpace(currentData)) { var command = JsonConvert.DeserializeObject <Values.NetworkCommand>(currentData); if (args.Path.ToLower() == ListenerPath.ToLower()) { switch (args.Type) { case Watcher.Event.EventType.NodeDataChanged: await _extractCommand.ExtractCommandMessage(command); break; } } } }); _isSubscribe = true; }
private void CreateBaseNode() { if (!client.ExistsAsync($"{BasePath}").Result) { try { client.CreatePersistentAsync($"{BasePath}", null).Wait(); } catch (AggregateException ex) { if (!(ex.InnerException is NodeExistsException)) { throw ex; } } } }
private static async Task CheckOrCreateRoot(IZookeeperClient zk) { bool exists = await zk.ExistsAsync(Root); if (!exists) { await zk.CreatePersistentAsync(Root, GetData("this is service register root")); } }
/// <summary> /// 构造函数 /// </summary> /// <param name="identity">当前锁的唯一标识</param> public ZKLockProvider(string identity) : base(identity) { ZKConfig = ZKConfig.New(); _zkClient = new ZookeeperClient(ZKConfig.ConnStr); if (_zkClient.ExistsAsync(NodeName).Result == false) { _zkClient.CreateRecursiveAsync(NodeName, ZKConfig.LockZKValue.Bytes()); } }
public async Task PublishCommandMessage(string applicationCode, NetworkCommand command) { var ListenerPath = $"/Bucket.Listener/{applicationCode}"; var existPath = await _client.ExistsAsync(ListenerPath); if (!existPath) { await _client.CreateRecursiveAsync(ListenerPath, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(command))); } await _client.SetDataAsync(ListenerPath, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(command))); }
public static async Task <bool> StrictExistsAsync(this IZookeeperClient zookeeperClient, string path) { try { return(await zookeeperClient.ExistsAsync(path)); } catch (Exception ex) { return(false); } }
private async Task <bool> SetRouteAsync(ServiceRouteDescriptor route, IZookeeperClient zooKeeperClient) { try { bool isSetRoute = false; _logger.LogDebug($"准备添加{route.ServiceDescriptor.Id}服务路由。"); var zooKeeperClients = await _zookeeperClientProvider.GetZooKeeperClients(); await CreateSubdirectory(zooKeeperClient, _configInfo.RoutePath); var path = _configInfo.RoutePath; if (!path.EndsWith("/")) { path += "/"; } var nodePath = $"{path}{route.ServiceDescriptor.Id}"; var nodeData = _serializer.Serialize(route); _logger.LogDebug($"服务路由内容为:{Encoding.UTF8.GetString(nodeData)}。"); if (!nodeWatchers.ContainsKey(nodePath)) { var watcher = nodeWatchers.GetOrAdd(nodePath, f => new NodeMonitorWatcher(path, async(oldData, newData) => await NodeChange(oldData, newData))); await zooKeeperClient.SubscribeDataChange(nodePath, watcher.HandleNodeDataChange); } if (!await zooKeeperClient.ExistsAsync(nodePath)) { _logger.LogDebug($"节点:{nodePath}不存在将进行创建。"); await zooKeeperClient.CreateAsync(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } else { var onlineData = (await zooKeeperClient.GetDataAsync(nodePath)).ToArray(); if (!DataEquals(nodeData, onlineData)) { await zooKeeperClient.SetDataAsync(nodePath, nodeData); _logger.LogDebug($"{nodePath}节点的缓存的服务路由与服务注册中心不一致,路由数据已被更新。"); isSetRoute = true; } } return(isSetRoute); } catch (Exception ex) { _logger.LogError($"{route.ServiceDescriptor.Id}服务的路由注册失败,原因:{ex.Message}"); return(false); } }
/// <summary> /// 创建或更新节点 /// 节点已存在则更新节点,否则直接创建节点 /// </summary> /// <param name="node">节点名称</param> /// <param name="value">节点数据</param> /// <returns>Task</returns> public Task CreateOrUpdateNode(string node, string value) { if (string.IsNullOrWhiteSpace(node) || node.StartsWith("/") == false) { return(Task.FromException(new Exception("无效的node"))); } if (string.IsNullOrWhiteSpace(value)) { return(Task.FromException(new Exception("无效的value"))); } if (_zkClient.ExistsAsync(node).Result) { return(_zkClient.SetDataAsync(node, Encoding.UTF8.GetBytes(value))); } else { return(CreateNode(node, value)); } }
public static async Task <IZookeeperClient> Register(ServiceInformation service) { IZookeeperClient zk = GetZooKeeper(); await CheckOrCreateRoot(zk); string servicesPath = $"{Root}/{service.Key}"; //todo 先获取后追加 if (!await zk.ExistsAsync(servicesPath)) { await zk.CreatePersistentAsync(servicesPath, GetData(string.Empty)); } string serviceNodePaht = $"{servicesPath}/{service.Host}:{service.Port}"; await zk.CreateEphemeralAsync(serviceNodePaht, GetData(service)); return(zk); }
private async Task CreatePath(string path, bool isParent) { if (isParent) { var exists = await client.ExistsAsync(path); if (exists) { return; } } var index = path.LastIndexOf('/'); if (index > 0) { await CreatePath(path.Substring(0, index), true); } await client.CreateAsync(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, isParent?CreateMode.PERSISTENT : CreateMode.EPHEMERAL); }
public async Task ExistsAsyncTest() { var result = await _client.ExistsAsync("/"); Assert.True(result); }
public async Task CreateRecursiveAndDeleteRecursiveTest() { var pathRoot = $"/{DateTime.Now:yyyy_MM_dd_HH_mm_ss_ff}"; var path = $"{pathRoot}/1/2"; if (await _client.ExistsAsync(pathRoot)) { await _client.DeleteRecursiveAsync(pathRoot); } await _client.CreateRecursiveAsync(path, null); Assert.True(await _client.ExistsAsync(path)); await _client.DeleteRecursiveAsync(pathRoot); if (await _client.ExistsAsync(pathRoot)) { throw new Exception("删除失败"); } }
public async Task ExistsAsyncTest() { var result = await _client.ExistsAsync("/"); }