微服务(入门二):netcore通过consul注册服务
基础准备
1.创建asp.net core Web 应用程序选择Api
2.appsettings.json 配置consul服务器地址,以及本机ip和端口号信息
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "Consul": { "IP": "127.0.0.1", "Port": "8500" }, "Service": { "Name": "zyz" }, "ip": "localhost", "port": "6655", "AllowedHosts": "*" }
3.程序入口(program.cs)配置useurls,ip和port从配置文件(或者命令行中)读取(命令行启动方式:dotnet ConsulServer.dll --ip localhost --port 8644)
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ConsulServer { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) { var config = new ConfigurationBuilder().AddCommandLine(args) .Build();//获取配置信息 return WebHost.CreateDefaultBuilder(args) .UseUrls($"http://{ config["ip"]}:{config["port"]}")//配置ip地址和端口地址 .UseStartup<Startup>(); } } }
4.配置基础数据,并且调用注册consul接口
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Consul; using ConsulServer.ConsulApi; using ConsulServer.entity; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace ConsulServer { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } ////配置信息单例 //ConfigSingleton.setConfigSingleton(Configuration); app.UseMvc(); ConsulEntity consulEntity = new ConsulEntity { ip = Configuration["ip"], port = int.Parse(Configuration["port"] ), ServiceName = "zyz", ConsulIP = Configuration["Consul:IP"], ConsulPort = Convert.ToInt32(Configuration["Consul:Port"]) }; app.RegisterConsul(lifetime, consulEntity); } } }
5.配置注册信息
using Consul; using ConsulServer.entity; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ConsulServer.ConsulApi { /// <summary> /// consul /// </summary> public static class AppBuilderExtensions { /// <summary> /// 注册consul /// </summary> /// <param name="app"></param> /// <param name="lifetime"></param> /// <param name="serviceEntity"></param> /// <returns></returns> public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, ConsulEntity serviceEntity) { //consul地址 Action<ConsulClientConfiguration> configClient = (consulConfig) => { consulConfig.Address = new Uri($"http://{serviceEntity.ConsulIP}:{ serviceEntity.ConsulPort}"); consulConfig.Datacenter = "dc1"; }; //建立连接 var consulClient = new ConsulClient(configClient); var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册 Interval = TimeSpan.FromSeconds(10),//健康监测 HTTP = string.Format($"http://{serviceEntity.ip}:{serviceEntity.port}/api/health"),//心跳检测地址 Timeout = TimeSpan.FromSeconds(5) }; //注册 var registrtion = new AgentServiceRegistration() { Checks = new[] { httpCheck }, ID = "zyzService" + Guid.NewGuid().ToString(),//服务编号不可重复 Name = serviceEntity.ServiceName,//服务名称 Address = serviceEntity.ip,//ip地址 Port = serviceEntity.port//端口 }; //注册服务 consulClient.Agent.ServiceRegister(registrtion); return app; } } }
6.以命令行启动程序查看consul(dotnet ConsulServer.dll --ip localhost --port 8644)