consul服务注册
项目结构:
admin和demo是两个demo api服务,gateway是一个ocelot网关。
本篇主要说明如何是admin api服务注册到consul中,并且ocelot如何中consul发现该服务。
第一步:在admin api服务配置如下图所示的Consul相关的配置:
第二步:创建一个如下所示的IHostedService服务,需安装:Winton.Extensions.Configuration.Consul包。
/// <summary> /// Consul注册 /// </summary> public class ConsulRegisterHostedService : IHostedService { private readonly ConsulClient _client; private readonly ConsulOption _option; public ConsulRegisterHostedService( IOptions<ConsulOption> option) { _option = option.Value; _client = new ConsulClient(x => { x.Address = new Uri(_option.ConsulAddress); }); } public async Task StartAsync(CancellationToken cancellationToken) { Console.WriteLine($"开始将{_option.ServiceName}服务注册到Consul中。"); await _client.Agent.ServiceDeregister(_option.ID, cancellationToken); await _client.Agent.ServiceRegister(new AgentServiceRegistration { ID = _option.ID, Name = _option.ServiceName, Address = _option.IP, Port = _option.Port, Tags = _option.Tags, Check = new AgentServiceCheck() { //服务启动多久后注册 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(0), //健康检查时间间隔 Interval = TimeSpan.FromSeconds(5), //健康检查地址 HTTP = $"http://{_option.IP}:{_option.Port}/{_option.HealthCheckAddress}", Timeout = TimeSpan.FromSeconds(5), } }, cancellationToken); Console.WriteLine($"注册{_option.ServiceName}服务到Consul成功。"); } public async Task StopAsync(CancellationToken cancellationToken) { await _client.Agent.ServiceDeregister(_option.ID, cancellationToken); Console.WriteLine($"从Consul中成功的注销了{_option.ServiceName}服务。"); } }
ConsulOption类如下所示:
public class ConsulOption { public string ID { get { return Guid.NewGuid().ToString(); } } /// <summary> /// 本服务IP /// </summary> public string IP { get; set; } = default!; /// <summary> /// 本服务端口 /// </summary> public int Port { get; set; } /// <summary> /// 本服务名称 /// </summary> public string ServiceName { get; set; } = default!; /// <summary> /// 健康检查地址 /// </summary> public string HealthCheckAddress { get; set; } = default!; /// <summary> /// Consul服务地址: http://ip:port or http://consulServiceName /// </summary> public string ConsulAddress { get; set; } = default!; public string[] Tags { get; set; } = default!; }
并将以上服务在main方法注册到Services中:
builder.Services.ConfigureAndValidate<ConsulOption>(builder.Configuration.GetSection("Consul")); builder.Services.AddHostedService<ConsulRegisterHostedService>();
builder.Services.AddHealthChecks();
第三步:添加一个Health方法给Cosul用于检测本服务是否在健康运行中,添加命名空间:using Microsoft.Extensions.Diagnostics.HealthChecks:
app.UseHealthChecks("/Health", new HealthCheckOptions { ResultStatusCodes = { [HealthStatus.Healthy] = StatusCodes.Status200OK, [HealthStatus.Degraded] = StatusCodes.Status503ServiceUnavailable, [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable } });
第四步:修改配置ocelot.json:
在使用consul服务发现之前,DownstreamHostAndPorts配置,现在可以删除它了,添加"ServiceName": "TaiPiAdmin",这行。
第五步:在ocelot.json的GlobalConfiguration节加上以下关于consul的相关的信息
大功造成:
接下来我们在Postman中发起对网关的请求:
在网关的命令窗口我们可以看到网关将对/api/admin/WeatherForecast的调用变成http://192.168.3.12:8001/WeatherForecast的调用
本文来自博客园,作者:追夢,转载请注明原文链接:https://www.cnblogs.com/koeltp/p/17254849.html