微服务 Consul 代码dome
一: consul 的 配置的有两种方式,这里主要介绍 通过代码 注册服务
Consul官网:https://www.consul.io/
Consul的主要功能有服务注册与发现、健康检查、K-V存储、多数据中心等。
- Consul安装:很简单,直接在官网下载解压即可。
- Consul运行:在consul.exe目录下打开命令行执行
consul.exe agent -dev
- 浏览器访问:http://localhost:8500/
分别建3个项目 Api.Catalog,Api.Ordering,Provider.Consul
Api.Catalog和Api.Ordering 服务结构 一样,端口可以用不同
using Consul; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Api.Catalog.Helper { public static class ConsulHelper { /// <summary> /// 服务注册到consul /// </summary> /// <param name="app"></param> /// <param name="lifetime"></param> public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime) { var consulClient = new ConsulClient(c => { //consul地址 c.Address = new Uri(configuration["ConsulSetting:ConsulAddress"]); }); var registration = new AgentServiceRegistration() { ID = Guid.NewGuid().ToString(),//服务实例唯一标识 Name = configuration["ConsulSetting:ServiceName"],//服务名 Address = configuration["ConsulSetting:ServiceIP"], //服务IP Port = int.Parse(configuration["ConsulSetting:ServicePort"]),//服务端口 因为要运行多个实例,端口不能在appsettings.json里配置,在docker容器运行时传入 Check = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册 Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔 HTTP = $"http://{configuration["ConsulSetting:ServiceIP"]}:{configuration["ConsulSetting:ServicePort"]}{configuration["ConsulSetting:ServiceHealthCheck"]}",//健康检查地址 Timeout = TimeSpan.FromSeconds(5)//等待时间 } }; //服务注册 consulClient.Agent.ServiceRegister(registration).Wait(); //应用程序终止时,取消注册 lifetime.ApplicationStopping.Register(() => { consulClient.Agent.ServiceDeregister(registration.ID).Wait(); }); return app; } } }
using Microsoft.AspNetCore.Mvc; namespace Api.Catalog.Controllers { [Route("[controller]")] [ApiController] public class HealthCheckController : ControllerBase { /// <summary> /// 健康检查接口 /// </summary> /// <returns></returns> [HttpGet] public IActionResult Get() => Ok(); } }
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace Api.Catalog.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { [HttpGet] public IEnumerable<string> Get() { return new string[] { "Api.Catalog1", "Api.Catalog2" }; } [HttpGet("{id}")] public string Get(int id) { return "Api.Catalog"; } } }
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConsulSetting": { "ServiceName": "CatalogService", "ServiceHealthCheck": "/healthcheck", "ConsulAddress": "http://localhost:8500", //注意,docker容器内部无法使用localhost访问宿主机器,如果是控制台启动的话就用localhost "ServiceIP": "localhost", "ServicePort": 52457 } }
Startup.cs
using Api.Catalog.Helper; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Api.Catalog { 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.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api.Catalog", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api.Catalog v1")); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); //服务注册 app.RegisterConsul(Configuration, lifetime); } } }
Provider.Consul 项目结构
ocelot.json 配置
{ "GlobalConfiguration": { //Ocelot应用地址 "BaseUrl": "http://localhost:2808", "ServiceDiscoveryProvider": { //Consul地址 "Host": "http://localhost/", //Consul端口 "Port": 8500, "Type": "Consul" //由Consul提供服务发现,每次请求Consul } }, "Routes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 52457 }, { "Host": "localhost", "Port": 41097 } ], "UpstreamPathTemplate": "/{everything}", "UpstreamHttpMethod": [ "Get", "Post" ], "LoadBalancerOptions": { "Type": "RoundRobin" } } ] }
Program.cs 配置
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Provider.Consul { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration(c => { c.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
Startup.cs 代码
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using Ocelot.DependencyInjection; using Ocelot.Middleware; using Ocelot.Provider.Consul; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Provider.Consul { 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.AddOcelot().AddConsul();//注入Ocelot服务 services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseOcelot(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
运行后的效果
参考地址:https://www.cnblogs.com/xhznl/p/13091750.html