| | |
| | | { |
| | | public void ConfigureServices(IServiceCollection services, IConfiguration config) |
| | | { |
| | | services.AddSingleton<IConsulClient, ConsulClient>(p => new ConsulClient(options => |
| | | { |
| | | var address = config["Consul:Address"] ?? "http://localhost:8500"; |
| | | options.Address = new Uri(address); |
| | | })); |
| | | services.AddComponent<DistributedCacheServiceComponent>(); |
| | | services.AddHttpRemote(); |
| | | services.AddSingleton<ResourceHttpUtils>(); |
| | | } |
| | | |
| | | public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration config) |
| | | { |
| | | var consulClient = app.ApplicationServices.GetRequiredService<IConsulClient>(); |
| | | var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>(); |
| | | |
| | | // 服务配置(从appsettings.json读取) |
| | | var serviceName = config["Consul:ServiceName"] ?? "UnknownService"; |
| | | var serviceHost = config["Consul:ServiceIP"] ?? "localhost"; |
| | | var servicePort = int.Parse(config["Consul:ServicePort"]); // 或直接用启动端口 |
| | | |
| | | // 服务唯一ID(避免同一服务多实例冲突) |
| | | var serviceId = $"{serviceName}-{serviceHost}-{servicePort}"; |
| | | |
| | | // 服务注册信息 |
| | | var registration = new AgentServiceRegistration |
| | | { |
| | | ID = serviceId, |
| | | Name = serviceName, |
| | | Address = serviceHost, |
| | | Port = servicePort, |
| | | // 健康检查配置 |
| | | Check = new AgentServiceCheck |
| | | { |
| | | HTTP = $"http://{serviceHost}:{servicePort}{config["Consul:ServiceHealthCheck"]}", |
| | | Interval = TimeSpan.FromSeconds(10), |
| | | Timeout = TimeSpan.FromSeconds(5), |
| | | DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(30) |
| | | } |
| | | }; |
| | | |
| | | // 注册服务 |
| | | consulClient.Agent.ServiceRegister(registration).Wait(); |
| | | |
| | | // 应用停止时注销服务 |
| | | lifetime.ApplicationStopping.Register(() => |
| | | { |
| | | consulClient.Agent.ServiceDeregister(serviceId).Wait(); |
| | | }); |
| | | } |
| | | } |
| | | } |