Consul
是一个用来实现分布式系统服务发现与配置的开源工具。它内置了服务注册与发现框架、分布一致性协议实现、健康检查、Key/Value存储、多数据中心方案,不再需要依赖其他工具,使用起来也较为简单。
Consul
官网:https://www.consul.io开源地址:https://github.com/hashicorp/consul、https://github.com/G-Research/consuldotnet
安装
Consul
支持各种平台的安装,安装文档:https://www.consul.io/downloads,为了快速使用,我这里选择用docker方式安装。
version: "3"
services:
service_1:
image: consul
command: agent -server -client=0.0.0.0 -bootstrap-expect=3 -node=service_1
volumes:
- /usr/local/docker/consul/data/service_1:/data
service_2:
image: consul
command: agent -server -client=0.0.0.0 -retry-join=service_1 -node=service_2
volumes:
- /usr/local/docker/consul/data/service_2:/data
depends_on:
- service_1
service_3:
image: consul
command: agent -server -client=0.0.0.0 -retry-join=service_1 -node=service_3
volumes:
- /usr/local/docker/consul/data/service_3:/data
depends_on:
- service_1
client_1:
image: consul
command: agent -client=0.0.0.0 -retry-join=service_1 -ui -node=client_1
ports:
- 8500:8500
volumes:
- /usr/local/docker/consul/data/client_1:/data
depends_on:
- service_2
- service_3
提供一个docker-compose.yaml
,使用docker-compose up
编排脚本启动Consul
,如果你不熟悉,可以选择其它方式能运行Consul
即可。
这里使用 Docker 搭建 3个 server 节点 + 1 个 client 节点,API 服务通过 client 节点进行服务注册和发现。
安装完成启动Consul
,打开默认地址 http://localhost:8500 可以看到Consul
ui界面。
快速使用
添加两个webapi服务,ServiceA和ServiceB,一个webapi客户端Client来调用服务。
dotnet new sln -n consul_demo
dotnet new webapi -n ServiceA
dotnet sln add ServiceA/ServiceA.csproj
dotnet new webapi -n ServiceB
dotnet sln add ServiceB/ServiceB.csproj
dotnet new webapi -n Client
dotnet sln add Client/Client.csproj
在项目中添加Consul
组件包
Install-Package Consul
服务注册
接下来在两个服务中添加必要的代码来实现将服务注册到Consul
中。
首先将Consul
配置信息添加到appsettings.json
{
"Consul": {
"Address": "http://host.docker.internal:8500",
"HealthCheck": "/healthcheck",
"Name": "ServiceA",
"Ip": "host.docker.internal"
}
}
因为我们要将项目都运行在docker中,所以这里的地址要用 host.docker.internal 代替,使用 localhost 无法正常启动,如果不在 docker 中运行,这里就配置层 localhost。
添加一个扩展方法UseConul(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime)
。
using System;
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace ServiceA
{
public static class Extensions
{
public static IApplicationBuilder UseConul(this IApplicationBuilder app, IConfigu