Consul是一个服务网格解决方案,提供了一个功能齐全的控制平面,具有服务发现、配置和分段功能。
下载安装Consul,直接去官网(Consul by HashiCorp)下载即可。
启动Consul,访问consul主页,默认为http://localhost:8500。
#开发模式启动consul agent -dev
将服务注册到Consul,首先需要下载consul的nuget包,在包管理器中,搜索consul进行安装,使用扩展方法封装一个通用的注册方法:
//ConsulRegistryExtensions.csusingConsul; usingMicrosoft.AspNetCore.Builder; usingMicrosoft.Extensions.Configuration; usingMicrosoft.Extensions.Hosting; namespaceConsulHelper{ publicstaticclassConsulRegistryExtensions { publicstaticIApplicationBuilderUseConul(thisIApplicationBuilderapplicationBuilder, IConfigurationconfiguration, IHostApplicationLifetimelifetime) { try { stringip=configuration["Consul:Ip"]; intport=Convert.ToInt32(configuration["Consul:Port"]); stringserviceName=configuration["Consul:ServiceName"]; varserviceId=Guid.NewGuid().ToString(); varconsulHost=configuration["Consul:ConsulHost"]; varconsulDataCenter=configuration["Consul:ConsulDataCenter"]; //创建consul的连接对象varconsulClient=newConsulClient(c=> { c.Address=newUri(consulHost); c.Datacenter=consulDataCenter; }); AgentServiceRegistrationagentServiceRegistration=newAgentServiceRegistration() { ID=serviceId, Name=serviceName, Address=ip, Port=port, Check=newAgentServiceCheck() { Interval=TimeSpan.FromSeconds(10), HTTP=$"http://{ip}:{port}/Api/ApiHealth", Timeout=TimeSpan.FromSeconds(10), DeregisterCriticalServiceAfter=TimeSpan.FromSeconds(20) } }; //将服务注册到consul上consulClient.Agent.ServiceRegister(agentServiceRegistration).Wait(); //注销实例lifetime.ApplicationStopped.Register(async () => { awaitconsulClient.Agent.ServiceDeregister(serviceId); }); } catch(Exceptionex) { } returnapplicationBuilder; } } }
配置文件中的参数配置:
"Consul": { "Ip": "127.0.0.1", "Port": "5272", "ServiceName": "ContentService", "ConsulHost": "http://127.0.0.1:8500", "ConsulDataCenter": "dc1" }
在WebApi项目的Controller文件夹中,创建心跳检测接口:
//ApiHealthController.csusingMicrosoft.AspNetCore.Mvc; namespaceContentService.WebApi.Controllers{ [Route("Api/[controller]")] publicclassApiHealthController:Controller { [HttpGet] publicIActionResultGet() { returnOk("ok"); } } }
在Program.cs中调用刚才我们写的扩展方法:
//服务注册到consul中IConfigurationconfiguration=app.Configuration; IHostApplicationLifetimelifetime=app.Lifetime; app.UseConul(configuration, lifetime);
启动服务,可以看到服务已经成功添加到Consul中了。