基礎準備 1.創建asp.net core Web 應用程式選擇Api 2.appsettings.json 配置consul伺服器地址,以及本機ip和埠號信息 3.程式入口(program.cs)配置useurls,ip和port從配置文件(或者命令行中)讀取(命令行啟動方式:dotnet Co ...
基礎準備
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)