赞
踩
Consul是HashiCorp公司推出的使用go语言开发的开源工具,用于实现分布式系统的服务发现与配置,内置了服务注册与发现框架、分布一致性协议实现、健康检查、Key/Value存储、多数据中心方案,使用起来较为简单。使用docker命令创建注册中心比较麻烦,并且不好维护,这里使用docker-compose来实现。registrator保证了,如果服务已停止,则从注册中心中移除。docker-compose.yaml如下
- version: "3.0"
-
- services:
- # consul server,对外暴露的ui接口为8500,只有在2台consul服务器的情况下集群才起作用
- consulserver:
- image: progrium/consul:latest
- hostname: consulserver
- ports:
- - "8300"
- - "8400"
- - "8500:8500"
- - "53"
- command: -server -ui-dir /ui -data-dir /tmp/consul --bootstrap-expect=3
-
- # consul server1在consul server服务起来后,加入集群中
- consulserver1:
- image: progrium/consul:latest
- hostname: consulserver1
- depends_on:
- - "consulserver"
- ports:
- - "8300"
- - "8400"
- - "8500"
- - "53"
- command: -server -data-dir /tmp/consul -join consulserver
-
- # consul server2在consul server服务起来后,加入集群中
- consulserver2:
- image: progrium/consul:latest
- hostname: consulserver2
- depends_on:
- - "consulserver"
- ports:
- - "8300"
- - "8400"
- - "8500"
- - "53"
- command: -server -data-dir /tmp/consul -join consulserver
- registrator:
- image: gliderlabs/registrator:master
- hostname: registrator
- depends_on:
- - "consulserver"
- volumes:
- - "/var/run/docker.sock:/tmp/docker.sock"
- command: -internal consul://consulserver:8500

然后运行docker-compose up -d
创建一个ServiceA(asp.net core 2.2) 项目,需要安装Consul,Consul包中提供了一个IConsulClient
类,我们可以通过它来调用Consul进行服务的注册,以及发现等。我们需要在服务启动的时候,将自身的地址等信息注册到Consul中,并在服务关闭的时候从Consul撤销。这种行为就非常适合使用 IHostedService 来实现。这里要注意的是,我们需要保证_serviceId
对于同一个实例的唯一,避免重复性的注册。关闭时撤销服务:ConsulHostedService.cs
- namespace ServiceA
- {
- using Consul;
- using Microsoft.AspNetCore.Hosting.Server;
- using Microsoft.AspNetCore.Hosting.Server.Features;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Linq;
- using System.Net;
- using System.Threading;
- using System.Threading.Tasks;
-
- public class ConsulHostedService : IHostedService
- {
- private readonly IConsulClient _consulClient;
- private readonly ILogger _logger;
- private readonly IServer _server;
-
- public ConsulHostedService(IConsulClient consulClient, ILogger<ConsulHostedService> logger, IServer server)
- {
- _c

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。