.NET微服務從0到1:服務註冊與發現(Consul)
阿新 • • 發佈:2020-03-08
[toc]
# Consul搭建
## 基於Docker搭建Consul
*以下為單機環境構建指令碼,用於本機測試,生產環境中應當進行叢集搭建*
```yml
version: '3'
services:
consul:
image: consul:1.7.1
container_name: consul
volumes:
- /c/docker/consul/data:/consul/data
- /c/docker/consul:/consul/config
ports:
- 8300:8300
- 8301:8301
- 8301:8301/udp
- 8302:8302
- 8302:8302/udp
- 8400:8400
- 8500:8500
- 53:53/udp
command: agent -server -bind=0.0.0.0 -client=0.0.0.0 -node=consul_Server1 -bootstrap-expect=1 -ui
```
成功搭建後,訪問8500埠,你可以看到如下介面
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20200307230813576.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW9idzgzMQ==,size_16,color_FFFFFF,t_70)
## 基於Windows搭建Consul
[點選](https://releases.hashicorp.com/consul/1.7.1/consul_1.7.1_windows_amd64.zip)下載Consul
執行以下命令執行consul
```cmd
consul agent -dev
```
# ServiceA整合Consul做服務註冊
*配置前一篇文章中的ServiceA*
> Install-Package Consul -Version 0.7.2.6
- Consul配置模型
```csharp
public class ServiceDisvoveryOptions
{
public string ServiceName { get; set; }
public ConsulOptions Consul { get; set; }
}
public class ConsulOptions
{
public string HttpEndpoint { get; set; }
public DnsEndpoint DnsEndpoint { get; set; }
}
public class DnsEndpoint
{
public string Address { get; set; }
public int Port { get; set; }
public IPEndPoint ToIPEndPoint()
{
return new IPEndPoint(IPAddress.Parse(Address), Port);
}
}
```
- 新增appsetting.json
```json
"ServiceDiscovery": {
"ServiceName": "ServiceA",
"Consul": {
"HttpEndpoint": "http://127.0.0.1:8500",
"DnsEndpoint": {
"Address": "127.0.0.1",
"Port": 8600
}
}
}
```
- Consul服務註冊實現
```csharp
private void ConfigureConsul(IApplicationBuilder app,