.NET5微服务示例-Consul注册中心
Consul官方网址:https://www.consul.io/
Consul有关介绍:https://www.cnblogs.com/shanyou/p/4695131.html
本文代码,文章结尾处提供下载。
一、安装Consul
1.官网下载对应版本,并解压出来
2.打开cmd,cd到解压的目录,运行为开发模式(或者翻到底下附录,通过配置文件运行)
//默认ip地址使用127.0.0.1 consul agent -dev //或者指定ip地址 consul.exe agent -dev -client x.x.x.x
3.命令运行成功后,打开“http://127.0.0.1:8500/”,出现页面即为成功
二、编写代码
1、整体代码结构:
2、SGZ.Framework整体结构介绍
3、SGZ.DepartmentService(部门服务)介绍,SGZ.PersonnelService(人员服务)同理
3.1、整体结构
3.2、只放了一个获取列表的接口
using Microsoft.AspNetCore.Mvc; using SGZ.Framework.Models; using System.Collections.Generic; namespace SGZ.DepartmentService.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class DepartmentController : ControllerBase { [HttpGet] public IActionResult GetList() { var list = new List<DepartmentDto> { new DepartmentDto{ ID = "D001", Name = "部门1" }, new DepartmentDto{ ID = "D002", Name = "部门2" }, new DepartmentDto{ ID = "D003", Name = "部门3" }, new DepartmentDto{ ID = "D004", Name = "部门4" }, new DepartmentDto{ ID = "D005", Name = "部门5" } }; return Ok(list); } } }
3.3、健康检查(有结果就行,不需要其它实现)
using Microsoft.AspNetCore.Mvc; using System; namespace SGZ.DepartmentService.Controllers { [Route("[controller]")] [ApiController] public class HealthCheckController : ControllerBase { [HttpGet] public IActionResult Get() { return Ok(DateTime.UtcNow.ToString()); } } }
3.4、appsettings.json加入一段配置
"ConsulConfigs": { //数据中心名称 "DataCenter": "dc1", //Consul地址 "RegistryAddress": "http://127.0.0.1:8500", //健康检查地址 "HealthCheckAddress": "/HealthCheck", "ServiceName": "DepartmentService", "ServiceScheme": "http", "ServiceAddress": "192.168.2.119", "ServicePort": 551 }
3.5、Program.cs的CreateHostBuilder函数改造,绑定配置文件中的地址
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", true).Build(); string serviceScheme = configuration["ConsulConfigs:ServiceScheme"]; string serviceAddress = configuration["ConsulConfigs:ServiceAddress"]; string servicePort = configuration["ConsulConfigs:ServicePort"]; if (!string.IsNullOrEmpty(serviceScheme) && !string.IsNullOrEmpty(serviceAddress) && !string.IsNullOrEmpty(servicePort)) { webBuilder.UseUrls($"{serviceScheme}://{serviceAddress}:{servicePort}"); } });
3.6、Startup.cs加入两项
4、SGZ.AggregationService(聚合服务)介绍
4.1、整体结构;因为没有设计这个聚合服务有上游,所以它不需要注册到Consul,也就是不需要健康检查了
4.2、获取部门服务和人员服务的数据,整合后再返回
[Route("api/[controller]")] [ApiController] public class AggregationController : ControllerBase { private readonly IServiceRequest _request; public AggregationController(IServiceRequest request) { _request = request; } [HttpGet] public async Task<IActionResult> Get() { //var departmentList = await _request.GetAsync<List<DepartmentDto>>("DepartmentService", "/api/Department/GetList"); //var personnelList = await _request.GetAsync<List<DepartmentDto>>("PersonnelService", "/api/Personnel/GetList"); //var list = new { departmentList, personnelList }; var departmentResult = await _request.GetAsync("DepartmentService", "/api/Department/GetList"); var personnelResult = await _request.GetAsync("PersonnelService", "/api/Personnel/GetList"); var obj = new { departmentResult, personnelResult }; return Ok(obj); } }
4.3、appsettings.json也只需加入这点配置
"ConsulConfigs": { "DataCenter": "dc1", "RegistryAddress": "http://127.0.0.1:8500" }
4.4、Startup.cs加入这几项
三、运行程序
1、不要以“IIS Express”的方式运行,不然不会使用“Program.cs”中绑定的地址
2、以部门服务为例,进入Debug文件夹,修改配置文件中的端口,打开cmd,运行“dotnet SGZ.DepartmentService.dll”,这样就跑起一个部门服务的集群了,然后可以测试你的负载均衡是否OK
3、三个服务都运行起来后,再访问聚合服务的接口“/api/Aggregation”,即可看到返回的数据
附录、Consul的集群搭建
1、准备3个节点
2、每个节点里面只有一个json配置文件,Consul配置大全:https://www.cnblogs.com/sunsky303/p/9209024.html
3、以node1为主节点,其配置如下
{ #数据中心名称 "datacenter": "dc1", #节点所在目录 "data_dir": "D:/consul/node1", #日志等级 "log_level": "INFO", #生产模式 "server": true, "node_name": "node1", #主节点有界面就行了,从节点不需要这个选项 "ui": true, "bind_addr": "127.0.0.1", "client_addr": "127.0.0.1", "advertise_addr": "127.0.0.1", #表示要3个节点才能跑 "bootstrap_expect": 3, "ports": { "http": 8500, "dns": 8600, "server": 8300, #记住这个端口,配置从节点的时候需要 "serf_lan": 8301, "serf_wan": 8302 } }
4、node2和node3为设置为从节点,配置相似,如下
{ "datacenter": "dc1", "data_dir": "D:/consul/node2", "log_level": "INFO", "server": true, "node_name": "node2", "bind_addr": "127.0.0.1", "client_addr": "127.0.0.1", "advertise_addr": "127.0.0.1", "ports": { "http": 8510, "dns": 8610, "server": 8310, "serf_lan": 8311, "serf_wan": 8312 } }
5、回到“D:/consul”目录,打开cmd
5.1、搭建主节点
consul agent -config-file=D:/consul/node1/basic.json
5.2、搭建从节点,两个从节点相似,就是需要改下路径;后面的8301,就是主节点配置的“serf_lan”端口
consul agent -config-file=D:/consul/node2/basic.json -retry-join=127.0.0.1:8301
5.3、运行起3个节点后,再打开“http://127.0.0.1:8500/”,发现consul的数量变为3了,端口也为刚才配置的
5.4、使用Nginx做负载均衡示例
本文代码:https://files.cnblogs.com/files/shousiji/net5_consul.rar