1.Consul的下载
下载地址:https://developer.hashicorp.com/consul/install
consul的官网:https://www.consul.io/api/agent/service.html
2.解压之后配置环境变量
3.启动Consul
第一种:在启动consul的时候,node参数可以写成 -node=127.0.0.1
consul agent -server -ui -bootstrap-expect=1 -data-dir=D:\\Tools\\consul_1.20.1_windows_amd64 -node=127.0.0.1 -client=0.0.0.0 -bind=127.0.0.1 -datacenter=dc1 -retry-join 127.0.0.1
第二种:在启动consul的时候,node参数可写成"hostname",在Hosts文件中对,node参数添加dns解析.
consul agent -server -ui -bootstrap-expect=1 -data-dir=D:\\Tools\\consul_1.20.1_windows_amd64 -node=hostname -client=0.0.0.0 -bind=127.0.0.1 -datacenter=dc1 -retry-join 127.0.0.1
window hosts文件位置:C:\Windows\System32\drivers\etc
在hosts文件中添加一行"127.0.0.1 hostname",即可
停止服务:consul.exe leave
4.实现
4.1 Snai.ApiGateway 配置
Ocelot.json
{
"Routes": [
{
"UpstreamPathTemplate": "/ApiService/{url}",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/ApiService/{url}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"host": "localhost",
"port": 5011
},
{
"host": "localhost",
"port": 5012
}
],
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"ServiceName": "consul_test",
"UseServiceDiscovery": true
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000",
"ServiceDiscoveryProvider": {
"Scheme": "http",
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
}
}
4.2 Snai.ApiServiceA
ConsulHelper
public static class ConsulHelper
{
/// <summary>
/// 将当前站点注入到Consul
/// </summary>
/// <param name="configuration"></param>
public static void ConsulRegister(this IConfiguration configuration)
{
string consulUrl = configuration["ConsulConfig:ConsulUrl"];
string serviceHost = configuration["ConsulConfig:Service:Host"];
string serviceSchame = configuration["ConsulConfig:Service:Schame"];
int servicePort = int.Parse(configuration["ConsulConfig:Service:Port"]);
ConsulClient client = new ConsulClient(c => {
c.Address = new Uri(consulUrl);
c.Datacenter = "dc1";
});
client.Agent.ServiceRegister(new AgentServiceRegistration
{
ID = configuration["ConsulConfig:Service:ID"], //注册进Consul后给个唯一id,
Name = configuration["ConsulConfig:Service:Name"], //站点做集群时,Name作为该集群的群名,
Address = serviceHost,
Port = servicePort,
Tags = configuration["ConsulConfig:Service:Tags"].Split(",").ToArray(), //标签
Check = new AgentServiceCheck
{
HTTP = $"{serviceSchame}://{serviceHost}:{servicePort}{configuration["ConsulConfig:Service:CheckAddress"]}",//这是你要让他定期访问的地址 返回一个ok就行
TLSSkipVerify = false,
Interval = TimeSpan.FromSeconds(10),//间隔10秒一次
Timeout = TimeSpan.FromSeconds(5),//检测等待时间
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60)//失败多久后移除,最小值60秒
}
});
}
}