1、微服务--为什么有consul,consul注册,心跳检测,服务发现
一、为什么有consul?
在微服务,每1个服务都是集群式的,订单服务在10台服务器上都有,那么用户的请求到达,获取哪台服务器的订单服务呢?如果10台中的有的订单服务挂了怎么办?10台服务器扛不住了,水平扩展又新增加了1台服务器提供订单服务,怎么让用户请求知道有新的服务器提供服务了?这时候就需要consul了,它能通过心跳检测哪些服务还活着,而且有新的服务启动,它也能主动发现
二、consul环境准备
1、consul环境
consul官网:https://www.consul.io/downloads.html,下载windows 64bit
2、启动consul管理后台
然后cmd启动,注意切盘符,路径要对,盘符切到放consul.exe的目录,cd d:\consul\consul agent -dev
访问consul管理后台:http://localhost:8500
三、代码实现
1、添加webapi服务
namespace consulservicefind.controllers { [route("api/[controller]")] [apicontroller] public class valuescontroller : controllerbase { private iconfiguration _iconfiguration = null; private ilogger<valuescontroller> _logger = null; public valuescontroller(iconfiguration iconfiguration, ilogger<valuescontroller> logger) { _iconfiguration = iconfiguration; _logger = logger; } // get api/values [httpget] public actionresult<ienumerable<string>> get() { this._logger.logwarning("valuescontroller-get 执行"); return new jsonresult(new { id = 123, name = "david_test", ip = this._iconfiguration["ip"], port = this._iconfiguration["port"], urls = this._iconfiguration["urls"], currentpath = base.httpcontext.request.path }); } } }
2、log4net 集成到core
2.1、nuget引入log4net
2.2、nuget引入microsoft.extensions.logging.log4net.aspnetcore
2.3、添加log4net 配置文件 (设置配置文件属性为始终复制,默认配置文件放在根目录下)
2.4、注入ilogger
namespace consulservicefind { public class program { public static void main(string[] args) { createwebhostbuilder(args).build().run(); } public static iwebhostbuilder createwebhostbuilder(string[] args) => webhost.createdefaultbuilder(args) .configurelogging((context, loggingbuilder) =>//ilogger { loggingbuilder.addfilter("system", loglevel.warning); // 忽略系统的其他日志 loggingbuilder.addfilter("microsoft", loglevel.warning); loggingbuilder.addlog4net(); }) .usestartup<startup>(); } }
3、网站启动后需要consul注册
3.1、nuget引用consul,consulregister类
namespace consulservicefind { public static class consulregister { public static void registconsul(this iconfiguration configuration) { string ip = configuration["ip"] ?? "localhost"; //部署到不同服务器的时候不能写成127.0.0.1或者0.0.0.0,因为这是让服务消费者调用的地址 int port = int.parse(configuration["port"]); //实例化consul客户端 consulclient consulclient = new consulclient(c => { c.address = new uri("http://127.0.0.1:8500"); c.datacenter = "consul"; }); //向consul注册服务 task<writeresult> result = consulclient.agent.serviceregister(new agentserviceregistration() { id = "david_webapi_test_" + guid.newguid(),//服务编号,不能重复 name = "david_webapi",//服务的名字--将来调用时用的就是这个 address = ip, port = port, tags = new string[] { },//可以用来设置权重 check=new agentservicecheck() { deregistercriticalserviceafter = timespan.fromseconds(5),//服务停止多久后反注册 interval = timespan.fromseconds(10),//健康检查时间间隔,或者称为心跳间隔 http = $"http://{ip}:{port}/api/health",//健康检查地址, timeout = timespan.fromseconds(5) } }); } } }
3.2、在startup的configure方法里使用consul
3.3、consulregister心跳检测,添加health-check,健康检查
namespace consulservicefind { [route("api/[controller]")] [apicontroller] public class healthcontroller : controllerbase { private iconfiguration _iconfiguration = null; private ilogger<healthcontroller> _logger = null; public healthcontroller(iconfiguration configuration, ilogger<healthcontroller> logger) { this._iconfiguration = configuration; this._logger = logger; } [httpget] public iactionresult check() { this._logger.logwarning($"{this._iconfiguration["port"]}-health check!"); return ok();//200 } } }
4、启动多个webapi实例,运行两个webapi服务起来
4.1、cd 切路径--c:\users\dell\desktop\consulservicefind\consulservicefind\bin\debug\netcoreapp2.2
4.2、通过命令行启动2个不同端口的webapi
dotnet consulservicefind.dll --urls="http://*:10010" --ip="127.0.0.1" --port=10010
dotnet consulservicefind.dll --urls="http://*:10020" --ip="127.0.0.1" --port=10020
http://localhost:10010/api/values
http://localhost:10020/api/values
4.3、去http://localhost:8500查看多个服务被发现和心跳检测