public void Dispose() { cacheServiceNode.Clear(); cacheServiceNodeTime.Clear(); timer?.Dispose(); _client?.Dispose(); }
/// <summary> /// 释放资源 /// </summary> public void Dispose() { if (consulClient != null) { consulClient.Dispose(); } }
/// <summary> /// 注册服务 /// </summary> /// <param name="config"></param> public void RegistryService(ServiceRegistryConfig config) { var client = new ConsulClient(option => { option.Address = new Uri(config.RegistryAddress); }); var registration = new AgentServiceRegistration { ID = config.Id, Name = config.Name, Address = config.Address, Port = config.Port, Tags = config.Tags, Check = new AgentServiceCheck { // 3.1、consul健康检查超时间 Timeout = TimeSpan.FromSeconds(10), // 3.2、服务停止5秒后注销服务 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 3.3、consul健康检查地址 HTTP = config.HealthCheckAddress, // 3.4 consul健康检查间隔时间 Interval = TimeSpan.FromSeconds(10), } }; client.Agent.ServiceRegister(registration).Wait(); client.Dispose(); }
/// <summary> /// 注册服务 /// </summary> /// <param name="registryConfig"></param> public void Registry(ServiceRegistryConfig registryConfig) { //创建客户端 var consulClient = new ConsulClient(config => { config.Address = new Uri(registryConfig.RegistryAddress); }); //创建consul注册对象 var registration = new AgentServiceRegistration() { ID = registryConfig.Id, Address = registryConfig.Address, Name = registryConfig.Name, Port = registryConfig.Port, Tags = registryConfig.Tags, //健康检查设置 Check = new AgentServiceCheck() { // 3.1、consul健康检查超时间 Timeout = TimeSpan.FromSeconds(10), // 3.2、服务停止5秒后注销服务 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 3.3、consul健康检查地址 HTTP = registryConfig.HealthCheckAddress, // 3.4 consul健康检查间隔时间 Interval = TimeSpan.FromSeconds(10), } }; //注册服务 consulClient.Agent.ServiceRegister(registration).Wait(); //注册完毕后关闭连接 consulClient.Dispose(); }
/// <summary> /// 服务注册 /// </summary> public void Register() { //1 创建consul客户端连接 var consulClient = new ConsulClient(configuration => { configuration.Address = new Uri(serviceRegistryOptions.RegistryAddress); }); //2 获取服务地址 var uri = new Uri(serviceRegistryOptions.ServiceAddress); //3 创建consul服务注册对象 var registration = new AgentServiceRegistration() { ID = string.IsNullOrEmpty(serviceRegistryOptions.ServiceId) ? Guid.NewGuid().ToString() : serviceRegistryOptions.ServiceId, Name = serviceRegistryOptions.ServiceName, Address = uri.Host, Port = uri.Port, Tags = serviceRegistryOptions.ServiceTags, Check = new AgentServiceCheck { Timeout = TimeSpan.FromSeconds(10), DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), HTTP = $"{uri.Scheme}://{uri.Host}:{uri.Port}{serviceRegistryOptions.HealthCheckAddress}", Interval = TimeSpan.FromSeconds(10), } }; //4 注册服务 consulClient.Agent.ServiceRegister(registration).Wait(); Console.WriteLine($"服务注册成功:{serviceRegistryOptions.ServiceAddress}"); //5 关闭连接 consulClient.Dispose(); }
/// <summary> /// Disposes of the client. /// </summary> /// <param name="disposing">If we are disopsing.</param> protected override void Dispose(bool disposing) { if (disposing) { client.Dispose(); } }
public async Task Cancelling_A_Token_When_Acquiring_A_Lock_Should_Throw_TaskCanceledException() { var keyName = Path.GetRandomFileName(); var masterClient = new ConsulClient(c => { c.Token = TestHelper.MasterToken; c.Address = TestHelper.HttpUri; }); var distributedLock2 = masterClient.CreateLock(new LockOptions(keyName) { SessionTTL = TimeSpan.FromSeconds(DefaultSessionTTLSeconds), LockWaitTime = TimeSpan.FromSeconds(LockWaitTimeSeconds) }); var distributedLock = _client.CreateLock(new LockOptions(keyName) { SessionTTL = TimeSpan.FromSeconds(DefaultSessionTTLSeconds), LockWaitTime = TimeSpan.FromSeconds(LockWaitTimeSeconds) }); await distributedLock2.Acquire(); // Become "Master" with another instance first var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await Assert.ThrowsAsync <TaskCanceledException>(async() => await distributedLock.Acquire(cts.Token)); await distributedLock2.Release(); await distributedLock2.Destroy(); masterClient.Dispose(); }
private static string AddTenant(this IApplicationBuilder app, string serviceName, string version, Uri uri, Uri healthCheckUri = null, IEnumerable <string> tags = null) { if (app == null) { throw new ArgumentNullException(nameof(app)); } var consulClient = new ConsulClient(configuration => { configuration.Address = new Uri(ConfigManagerConf.GetValue("ServiceDiscovery:Consul:HttpEndpoint")); }); string check = healthCheckUri?.ToString() ?? $"{uri}".TrimEnd('/') + "/health"; string versionLabel = $"{VERSION_PREFIX}{version}"; var tagList = (tags ?? Enumerable.Empty <string>()).ToList(); tagList.Add(versionLabel); var registration = new AgentServiceRegistration() { ID = Guid.NewGuid().ToString(), Name = serviceName, Address = uri.Host, Port = uri.Port, Tags = tagList.ToArray(), Check = new AgentServiceCheck { // 3.1、consul健康检查超时间 Timeout = TimeSpan.FromSeconds(10), // 3.2、服务停止_后注销服务 DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(10), // 3.3、consul健康检查地址 HTTP = check, // 3.4 consul健康检查间隔时间 Interval = TimeSpan.FromSeconds(10), } }; string id = registration.ID; var allService = consulClient.Catalog.Service(ConfigManagerConf.GetValue("ServiceDiscovery:ServiceName")).GetAwaiter().GetResult(); var regService = allService.Response.FirstOrDefault(x => x.Address == registration.Address && x.ServicePort == registration.Port); if (regService == null) { Console.WriteLine($"注册的serviceid:{registration.ID}"); consulClient.Agent.ServiceRegister(registration).Wait(); } else { id = regService.ServiceID; } consulClient.Dispose(); return(id); }
private void Dispose(bool disposing) { DeregisterServiceAsync(deregistration).Wait(); if (disposing) { client?.Dispose(); } }
public void Dispose() { if (_disposed) { return; } ConsulClient?.Dispose(); _disposed = true; }
private void Dispose(bool disposing) { if (disposing) { if (!_wasExistingClient) { _client.Dispose(); } } }
public async Task Cancelling_A_Token_When_Acquiring_A_Lock_Respects_The_Token() { var keyName = Path.GetRandomFileName(); var masterInstanceClient = new ConsulClient(c => { c.Token = TestHelper.MasterToken; c.Address = TestHelper.HttpUri; }); // Arrange var distributedLock2 = masterInstanceClient.CreateLock(new LockOptions(keyName) { SessionTTL = TimeSpan.FromSeconds(DefaultSessionTTLSeconds), LockWaitTime = TimeSpan.FromSeconds(LockWaitTimeSeconds) }); var distributedLock = _client.CreateLock(new LockOptions(keyName) { SessionTTL = TimeSpan.FromSeconds(DefaultSessionTTLSeconds), LockWaitTime = TimeSpan.FromSeconds(LockWaitTimeSeconds) }); var cancellationOperationTimer = new Stopwatch(); // Act await distributedLock2.Acquire(); // Become "Master" with another instance first cancellationOperationTimer.Start(); var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); try { await distributedLock.Acquire(cts.Token); } catch (Exception) { } cancellationOperationTimer.Stop(); // Assert var stopTimeMs = cancellationOperationTimer.ElapsedMilliseconds; var lockWaitTimeMs = TimeSpan.FromSeconds(LockWaitTimeSeconds).TotalMilliseconds; Assert.True(stopTimeMs < lockWaitTimeMs); // cleanup await distributedLock2.Release(); if (distributedLock.IsHeld) { await distributedLock2.Release(); } await distributedLock2.Destroy(); masterInstanceClient.Dispose(); }
public void Deregister() { var consulClient = new ConsulClient(configuration => { configuration.Address = new Uri(serviceRegistryOptions.RegistryAddress); }); consulClient.Agent.ServiceDeregister(serviceRegistryOptions.ServiceId).Wait(); Console.WriteLine($"服务注销成功:{serviceRegistryOptions.ServiceAddress}"); consulClient.Dispose(); }
/// <summary> /// 服务注销 /// </summary> /// <param name="serviceNode"></param> public void DeRegister(ServiceRegistryConfig serviceNode) { //1,创建客户端连接 var consulclient = new ConsulClient(config => { //1.1建立客户端与服务端的连接 config.Address = new Uri(serviceNode.Address); }); //2.注销服务 consulclient.Agent.ServiceDeregister(serviceNode.Id); //3 关闭连接 consulclient.Dispose(); }
public void DeRegister() { //1.建立客户端连接 var consulClient = new ConsulClient(config => { config.Address = new Uri(serviceRegistryOptions.RegistryAddress); }); //2.注销服务 consulClient.Agent.ServiceDeregister(serviceRegistryOptions.ServiceId).Wait(); Console.WriteLine($"服务注销成功:{serviceRegistryOptions.ServiceAddress}"); //3.关闭连接 consulClient.Dispose(); }
public async Task Client_DisposeBehavior() { var opts = new WriteOptions() { Datacenter = "foo", Token = "12345" }; _client.Dispose(); var request = _client.Put("/v1/kv/foo", new KVPair("kv/foo"), opts); await Assert.ThrowsAsync <ObjectDisposedException>(() => request.Execute(CancellationToken.None)); }
/// <summary> /// 注销服务 /// </summary> /// <param name="registryConfig"></param> public void Deregister(ServiceRegistryConfig registryConfig) { //创建Consul连接 var consulClient = new ConsulClient(config => { //建立客户端和服务端的连接 config.Address = new Uri(registryConfig.RegistryAddress); }); //注销该服务,根据服务的Id进行注销 consulClient.Agent.ServiceDeregister(registryConfig.Id); //注销后关闭当前连接 consulClient.Dispose(); }
/// <summary> /// 注销服务 /// </summary> /// <param name="serviceRegistryOption">服务注册配置信息</param> public void Deregister(ServiceRegistryOptions serviceRegistryOption) { // 1. 创建 Consul 客户端连接 var consulClient = new ConsulClient(config => { // 1.1 配置 Consul 服务端地址 config.Address = new Uri(serviceRegistryOption.Address); }); // 2. 注销服务 consulClient.Agent.ServiceDeregister(serviceRegistryOption.Id); // 3. 关闭连接 consulClient.Dispose(); }
/// <summary> /// 关闭 /// </summary> /// <returns></returns> async Task IMessageReceiver.Close() { //try //{ // subscribeObject?.Unsubscribe(); //} //catch (Exception ex) //{ // logger.Error(() => $"LoopBegin error.{ex.Message}"); //} try { client?.Dispose(); while (isBusy > 0)//等处理线程退出 { await Task.Delay(10); } } catch (Exception ex) { logger.Error(() => $"LoopBegin error.{ex.Message}"); } }
/// <summary> /// 注销服务 /// </summary> /// <param name="serviceNode"></param> public void Deregister(ServiceRegistryConfig serviceNode) { // 1、创建consul客户端连接 var consulClient = new ConsulClient(configuration => { //1.1 建立客户端和服务端连接 configuration.Address = new Uri(serviceNode.RegistryAddress); }); // 2、注销服务 consulClient.Agent.ServiceDeregister(serviceNode.Id); // 3、关闭连接 consulClient.Dispose(); }
/// <summary> /// 注销服务 /// </summary> /// <param name="settings"></param> public void Deregister(ConsulServiceOptions settings) { // 1. 创建Consul客户端链接 var consulClient = new ConsulClient(config => { // 1.1 建立客户端和服务端链接 config.Address = new Uri(settings.ConsulAddress); }); // 2. 注销服务 consulClient.Agent.ServiceDeregister(settings.ConsulAddress); // 3. 关闭链接 consulClient.Dispose(); }
async Task ILifeFlow.Close() { try { foreach (var ser in services) { var res = await consulClient.Agent.ServiceDeregister(ser.ID);//服务停止时取消注册 logger.Information(() => $"服务[{ser.Name}]反注册到Consul:{res.StatusCode}"); } consulClient?.Dispose(); } catch (Exception ex) { logger.Exception(ex); } }
public static void SetConsul(IConfiguration Configuration) { // 1、创建consul客户端连接 var consulClient = new ConsulClient(configuration => { //1.1 建立客户端和服务端连接 configuration.Address = new Uri(Configuration["ServiceDiscovery:Consul:HttpEndpoint"]); }); // 2、获取服务内部地址 // 3、创建consul服务注册对象 var registration = new AgentServiceRegistration() { ID = Guid.NewGuid().ToString(), Name = Configuration["ServiceDiscovery:ServiceName"], Address = Configuration["ServiceDiscovery:BindAddress"], Port = int.Parse(Configuration["ServiceDiscovery:Port"]), Tags = new string[] { "qqq", "www" }, Check = new AgentServiceCheck { // 3.1、consul健康检查超时间 Timeout = TimeSpan.FromSeconds(10), // 3.2、服务停止5秒后注销服务 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 3.3、consul健康检查地址 HTTP = $"http://{Configuration["ServiceDiscovery:BindAddress"]}:{Configuration["ServiceDiscovery:Port"]}/api/Health/Check", // 3.4 consul健康检查间隔时间 Interval = TimeSpan.FromSeconds(3), } }; var allService = consulClient.Catalog.Service(Configuration["ServiceDiscovery:ServiceName"]).GetAwaiter().GetResult(); if (!allService.Response.Any(x => x.Address == registration.Address && x.ServicePort == registration.Port)) { // 4、注册服务 Console.WriteLine($"注册的serviceid:{registration.ID}"); consulClient.Agent.ServiceRegister(registration).Wait(); } // 5、关闭连接 consulClient.Dispose(); }
public void Register(ConsulServiceOptions settings) { var logger = new LoggerConfiguration().WriteTo.Async(c => c.File( "Logs/logs1111.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 31, //默认就是31 shared: true)).CreateLogger(); // 1. 创建Consul客户端链接 var consulClient = new ConsulClient(config => { // 1.1 建立客户端和服务端链接 config.Address = new Uri(settings.ConsulAddress); }); // 2. 创建Consul服务注册对象 var registration = new AgentServiceRegistration() { ID = settings.ServiceId, Name = settings.ServiceName, Address = settings.ServiceAddress, Port = settings.ServicePort, Tags = settings.ServiceTags, Check = new AgentServiceCheck { // 2.1 Consul健康检查时间 Timeout = TimeSpan.FromSeconds(settings.HealthCheckTimeOut), // 2.2 服务停止5秒后注销服务 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 2.3 Consul健康检查地址 HTTP = settings.HealthCheckAddress, // 2.4 Consul健康检查间隔时间 Interval = TimeSpan.FromSeconds(settings.HealthCheckInterval), // 2.5 是否跳过传输层安全协议(Transport Layer Security),默认true TLSSkipVerify = true } }; logger.Information("准备注册"); // 3. 注册服务 consulClient.Agent.ServiceRegister(registration).Wait(); // 4. 关闭链接 consulClient.Dispose(); }
public static Server StartAndRegisterConsul(this Server server) { server.Start(); var ports = server.Ports; var srvNames = server.Services.GetServicesName(); try { var client = new ConsulClient(p => { p.Address = new Uri("http://127.0.0.1:8500"); }); client.Agent.ServiceRegister(new AgentServiceRegistration { Address = "127.0.0.1", Port = ports.First().BoundPort, Name = srvNames.First(), Tags = srvNames.ToArray(), Check = new AgentServiceCheck { //TTL=TimeSpan.FromSeconds(5), Status = HealthStatus.Passing, TCP = "127.0.0.1:50051", Interval = TimeSpan.FromSeconds(5) } }).Wait(); //client.Agent.CheckRegister(new AgentCheckRegistration //{ // DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1), // TTL = TimeSpan.FromSeconds(ServiceConfig.TCPInterval), // Status = HealthStatus.Passing, // ID = ServiceConfig.GetConsulServiceId() + ":ttlcheck", // ServiceID = ServiceConfig.GetConsulServiceId(), // Name = "ttlcheck" //}).Wait(); client.Dispose(); } catch (Exception ex) { InnerLogger.Log(LoggerLevel.Error, $"consul Register failed {Environment.NewLine}{ex.ToString()}"); } return(server); }
/// <summary> /// 注销服务 /// </summary> /// <param name="serviceNode"></param> public void Deregister() { // 1、创建consul客户端连接 var consulClient = new ConsulClient(configuration => { //1.1 建立客户端和服务端连接 configuration.Address = new Uri(serviceRegistryOptions.RegistryAddress); }); // 2、注销服务 consulClient.Agent.ServiceDeregister(serviceRegistryOptions.ServiceId).Wait(); Console.WriteLine($"服务注销成功:{serviceRegistryOptions.ServiceAddress}"); // 3、关闭连接 consulClient.Dispose(); }
/// <summary> /// 注册服务 /// </summary> public void Register() { // 1、创建consul客户端连接 var consulClient = new ConsulClient(configuration => { //1.1 建立客户端和服务端连接 configuration.Address = new Uri(serviceRegistryOptions.RegistryAddress); }); // 2、获取 var uri = new Uri(serviceRegistryOptions.ServiceAddress); // 3、创建consul服务注册对象 var registration = new AgentServiceRegistration() { ID = string.IsNullOrEmpty(serviceRegistryOptions.ServiceId) ? Guid.NewGuid().ToString() : serviceRegistryOptions.ServiceId, Name = serviceRegistryOptions.ServiceName, Address = uri.Host, Port = uri.Port, Tags = serviceRegistryOptions.ServiceTags, Check = new AgentServiceCheck { // 3.1、consul健康检查超时间 Timeout = TimeSpan.FromSeconds(10), // 3.2、服务停止5秒后注销服务 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 3.3、consul健康检查地址 HTTP = $"{uri.Scheme}://{uri.Host}:{uri.Port}{serviceRegistryOptions.HealthCheckAddress}", // 3.4 consul健康检查间隔时间 Interval = TimeSpan.FromSeconds(10), } }; // 4、注册服务 consulClient.Agent.ServiceRegister(registration).Wait(); Console.WriteLine($"服务注册成功:{serviceRegistryOptions.ServiceAddress}"); Console.WriteLine($"健康检查地址:{serviceRegistryOptions.HealthCheckAddress}"); // 5、关闭连接 consulClient.Dispose(); }
/// <summary> /// 构造函数 /// </summary> /// <param name="host"></param> /// <param name="port"></param> private ConsulKVManager(string host = "127.0.0.1", int port = 8500) { try { _consul = new ConsulClient(config => { config.Address = new Uri($"http://{host}:{port}"); }); } catch (Exception ex) { _consul.Dispose(); _consul = null; _consul = new ConsulClient(config => { config.Address = new Uri($"http://{host}:{port}"); }); } }
/// <summary> /// 反注册Consul /// </summary> /// <returns></returns> public void UnRegisterConsul() { if (!_consulConfig.Enable) { return; } OnMessage?.Invoke("开始反注册Consul"); try { consulClient.Dispose(); consulClient = null; consulID = null; OnMessage?.Invoke("Consul反注册完毕"); } catch (Exception exception) { exception = new MateralProjectException("Consul反注册失败", exception); OnException?.Invoke(exception); } }
/// <summary> /// 注册服务 /// </summary> /// <param name="serviceRegistryOption">服务注册配置信息</param> public void Register(ServiceRegistryOptions serviceRegistryOption) { // 1. 创建 Consul 客户端连接 var consulClient = new ConsulClient(config => { // 1.1 配置 Consul 服务端地址 config.Address = new Uri(serviceRegistryOption.RegistryAddress); }); // 2. 获取服务内部地址 // TODO... // 3. 创建 Consul 服务注册对象 var registration = new AgentServiceRegistration() { ID = serviceRegistryOption.Id, Name = serviceRegistryOption.Name, Address = serviceRegistryOption.Address, Port = serviceRegistryOption.Port, Tags = serviceRegistryOption.Tags, Check = new AgentServiceCheck() { // 3.1 Consul 健康检查超时时间 Timeout = TimeSpan.FromSeconds(serviceRegistryOption.Timeout), // 3.2 服务停止指定时间后执行注销 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(serviceRegistryOption.DeregisterAfterServiceStop), // 3.3 Consul 健康检查地址 HTTP = serviceRegistryOption.HealthCheckAddress, // 3.3.1 跳过证书验证 --> 未安装有效证书时,可以通过此参数跳过证书校验 TLSSkipVerify = true, // 3.4 Consul 健康检查间隔时间 Interval = TimeSpan.FromSeconds(serviceRegistryOption.HealthCheckInterval), } }; // 4. 注册服务 consulClient.Agent.ServiceRegister(registration).Wait(); // 5. 关闭连接 consulClient.Dispose(); }
public async Task Client_DisposeBehavior() { var client = new ConsulClient(); var opts = new WriteOptions() { Datacenter = "foo", Token = "12345" }; client.Dispose(); var request = client.Put("/v1/kv/foo", new KVPair("kv/foo"), opts); await Assert.ThrowsAsync<ObjectDisposedException>(() => request.Execute()); }