public AbstractServiceDiscovery(IOptions <ServiceDiscoveryOption> options) { this.serviceDiscoveryOption = options.Value; //1 创建consul客户端连接 var consulClient = new ConsulClient(configuration => { configuration.Address = new Uri(serviceDiscoveryOption.DiscoveryAddress); }); //2 consul先查询服务 var queryResult = consulClient.Catalog.Services().Result; if (!queryResult.StatusCode.Equals(HttpStatusCode.OK)) { throw new Exception($"consul连接失败:{queryResult.StatusCode}"); } //3 获取服务下的所有实例 foreach (var item in queryResult.Response) { QueryResult <CatalogService[]> result = consulClient.Catalog.Service(item.Key).Result; var list = new List <ServiceNode>(); foreach (var service in result.Response) { list.Add(new ServiceNode { Url = service.ServiceAddress + ":" + service.ServicePort }); } CacheConsulResult.Add(item.Key, list); } }
public ConsulBridgeRouter(IServiceDiscoveryProvider discovery, ITransportFactory <TMessage> transportFactory, IOptions <ServiceDiscoveryOption> options) { _discovery = discovery; _options = options.Value ?? ServiceDiscoveryOption.Default; _transportFactory = transportFactory; Initialize(); }
public static IApplicationBuilder UseConsulRegisterService(this IApplicationBuilder app, IConfiguration configuration) { ServiceDiscoveryOption serviceDiscoveryOption = new ServiceDiscoveryOption(); configuration.GetSection("ServiceDiscovery").Bind(serviceDiscoveryOption); app.UseConsulRegisterService(serviceDiscoveryOption); return(app); }
private static IApplicationBuilder UseConsulRegisterService(this IApplicationBuilder app, ServiceDiscoveryOption serviceDiscoveryOption, IConsulClient consul, IApplicationLifetime lifetime) { var loggerFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger("ServiceBuilder"); IEnumerable <Uri> addresses = null; if (serviceDiscoveryOption.Endpoints != null && serviceDiscoveryOption.Endpoints.Length > 0) { logger.LogInformation($"Using {serviceDiscoveryOption.Endpoints.Length} configured endpoints for service registration"); addresses = serviceDiscoveryOption.Endpoints.Select(p => new Uri(p)); } else { logger.LogInformation($"Trying to use server.Features to figure out the service endpoint for registration."); var features = app.Properties["server.Features"] as FeatureCollection; addresses = features.Get <IServerAddressesFeature>().Addresses.Select(p => new Uri(p)).ToArray(); } if (serviceDiscoveryOption.HealthCheck == null) { serviceDiscoveryOption.HealthCheck = new HealthCheckOption(); } foreach (var address in addresses) { var serviceId = $"{serviceDiscoveryOption.ServiceName}_{address.Host}:{address.Port}"; var httpCheck = new AgentServiceCheck() { Interval = serviceDiscoveryOption.HealthCheck.Interval, HTTP = new Uri(address, serviceDiscoveryOption.HealthCheck.CheckUrl).OriginalString }; var registration = new AgentServiceRegistration() { Checks = new[] { httpCheck }, Address = address.Host, ID = serviceId, Name = serviceDiscoveryOption.ServiceName, Port = address.Port }; consul.Agent.ServiceRegister(registration).GetAwaiter().GetResult(); // register service & health check cleanup lifetime.ApplicationStopping.Register(() => { logger.LogInformation("Removing tenant & additional health check"); consul.Agent.ServiceDeregister(serviceId).GetAwaiter().GetResult(); }); } return(app); }
public static IServiceCollection AddServiceDiscovery(this IServiceCollection services, ServiceDiscoveryOption serviceDiscoveryOption) { //implement the consulclient and add to service container services.AddSingleton <IConsulClient>(p => new ConsulClient( cfg => { if (!string.IsNullOrEmpty(serviceDiscoveryOption.Consul.HttpEndpoint)) { cfg.Address = new Uri(serviceDiscoveryOption.Consul.HttpEndpoint); } } )); //implement the dns lookup and register to service container services.AddSingleton <IDnsQuery>(p => { var client = new LookupClient(IPAddress.Parse("127.0.0.1"), 8600); if (serviceDiscoveryOption.Consul.DnsEndpoint != null) { client = new LookupClient(serviceDiscoveryOption.Consul.DnsEndpoint.ToIPEndPoint()); } client.EnableAuditTrail = false; client.UseCache = true; client.MinimumCacheTimeout = TimeSpan.FromSeconds(1); return(client); }); return(services); }
//the method check the service discovery parameter register ipaddress to generate service agent //those service agents will deregister when the app stop public static IApplicationBuilder UseConsulRegisterService(this IApplicationBuilder app, ServiceDiscoveryOption serviceDiscoveryOption) { var applife = app.ApplicationServices.GetRequiredService <IApplicationLifetime>() ?? throw new ArgumentException("Missing Dependency", nameof(IApplicationLifetime)); if (serviceDiscoveryOption.Consul == null) { throw new ArgumentException("Missing Dependency", nameof(serviceDiscoveryOption.Consul)); } var consul = app.ApplicationServices.GetRequiredService <IConsulClient>() ?? throw new ArgumentException("Missing dependency", nameof(IConsulClient)); //create logger to record the important information var loggerFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger("ConsulCommonServiceBuilder"); if (string.IsNullOrEmpty(serviceDiscoveryOption.ServiceName)) { throw new ArgumentException("service name must be configure", nameof(serviceDiscoveryOption.ServiceName)); } IEnumerable <Uri> addresses = null; if (serviceDiscoveryOption.Endpoints != null && serviceDiscoveryOption.Endpoints.Length > 0) { logger.LogInformation($"Using {serviceDiscoveryOption.Endpoints.Length} configured endpoints for service registration"); addresses = serviceDiscoveryOption.Endpoints.Select(p => new Uri(p)); } else { logger.LogInformation($"Trying to use server.Features to figure out the service endpoint for registration."); var features = app.Properties["server.Features"] as FeatureCollection; addresses = features.Get <IServerAddressesFeature>().Addresses.Select(p => new Uri(p)).ToArray(); } logger.LogInformation($"Found{addresses.Count()} endpoints:{string.Join(",",addresses.Select(p=>p.OriginalString))}."); foreach (var address in addresses) { var serviceID = $"{serviceDiscoveryOption .ServiceName}_{address.Host}:{address.Port}"; logger.LogInformation($"Registering service {serviceID} for address {address}."); var serviceChecks = new List <AgentServiceCheck>(); if (!string.IsNullOrEmpty(serviceDiscoveryOption.HealthCheckTemplate)) { var healthCheckUri = new Uri(address, serviceDiscoveryOption.HealthCheckTemplate).OriginalString; serviceChecks.Add(new AgentServiceCheck() { Status = HealthStatus.Passing, DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1), Interval = TimeSpan.FromSeconds(5), HTTP = healthCheckUri }); logger.LogInformation($"Adding healthcheck for {serviceID},checking {healthCheckUri}"); } //generate the agent service var registration = new AgentServiceRegistration() { Checks = serviceChecks.ToArray(), Address = address.Host, ID = serviceID, Name = serviceDiscoveryOption.ServiceName, Port = address.Port }; consul.Agent.ServiceRegister(registration).GetAwaiter().GetResult(); applife.ApplicationStopping.Register(() => { consul.Agent.ServiceDeregister(serviceID).GetAwaiter().GetResult(); }); } return(app); }
public Startup(IConfiguration configuration) { _serviceDiscoveryOption = new ServiceDiscoveryOption(); Configuration = configuration.GetSection("ServiceDiscovery"); Configuration.Bind(_serviceDiscoveryOption); }
//Dependency injection transmit value public HomeController(IDnsQuery dns, IOptions <ServiceDiscoveryOption> serviceDiscoveryOption) { _dns = dns ?? throw new ArgumentException(nameof(dns)); _serviceDiscoveryOption = serviceDiscoveryOption.Value; }
public static IApplicationBuilder UseConsulRegisterService(this IApplicationBuilder app, ServiceDiscoveryOption serviceDiscoveryOption) { var applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>() ?? throw new ArgumentException("Missing Dependency", nameof(IApplicationLifetime)); if (string.IsNullOrEmpty(serviceDiscoveryOption.ServiceName)) { throw new ArgumentException("service name must be configure", nameof(serviceDiscoveryOption.ServiceName)); } Uri address = null; if (!string.IsNullOrWhiteSpace(serviceDiscoveryOption.Endpoint)) { address = new Uri(serviceDiscoveryOption.Endpoint); } else { var features = app.Properties["server.Features"] as FeatureCollection; address = features.Get <IServerAddressesFeature>()?.Addresses?.Select(p => new Uri(p))?.FirstOrDefault(); } if (address != null) { Uri healthCheck = null; if (!string.IsNullOrEmpty(serviceDiscoveryOption.HealthCheckTemplate)) { healthCheck = new Uri(serviceDiscoveryOption.HealthCheckTemplate); } var registryInformation = app.AddTenant(serviceDiscoveryOption.ServiceName, serviceDiscoveryOption.Version, address, serviceType: serviceDiscoveryOption.ServiceType, healthCheckUri: healthCheck, tags: new[] { $"urlprefix-/{serviceDiscoveryOption.ServiceName}" }); applicationLifetime.ApplicationStopping.Register(() => { app.RemoveTenant(registryInformation.Id); }); } return(app); }