Ocelot+Consul+.netcore高可用&动态伸缩
Ocelot 网关:
- publicclassStartup
- {
- publicStartup(IConfiguration configuration)
- {
- Configuration= configuration;
- }
- publicIConfigurationConfiguration{ get;}
- // This method gets called by the runtime. Use this method to add services to the container.
- publicvoidConfigureServices(IServiceCollection services)
- {
- var config =newConfigurationBuilder()
- .AddJsonFile("Ocelot.json",false,true)
- .Build();
- services.AddOcelot(config).AddConsul();
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
- //services.AddMvc(); -- no need MVC
- // Ocelot
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env)
- {
- if(env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- // Ocelot
- app.UseOcelot().Wait();
- app.UseMvc();//-- no need MVC
- }
- }
配置:
- {
- "ReRoutes":[
- {
- "ReRoutesCaseSensitive":false,
- "DownstreamPathTemplate":"/api/values",
- "DownstreamScheme":"http",
- "LoadBalancerOptions":{
- "Type":"RoundRobin"
- },
- "ServiceName":"MsgService",
- "UpstreamHttpMethod":["Get","Post"],
- "UpstreamPathTemplate":"/test",
- "UseServiceDiscovery":true
- }
- ],
- "GlobalConfiguration":{
- "RequestIdKey":"OcRequestId",
- "ServiceDiscoveryProvider":{
- "Host":"10.248.37.110",
- "Port":8500,
- "Type":"Consul"
- }
- }
- }
Consul配置:
- consul agent -data-dir D:\Tool\consul\tmp\node0 -node=node0 -bind=10.248.37.110-datacenter=dc1 -ui -client=10.248.37.110-server -bootstrap-expect 1
.net core web注册:
- publicclassStartup
- {
- publicStartup(IConfiguration configuration)
- {
- Configuration= configuration;
- }
- publicIConfigurationConfiguration{ get;}
- // This method gets called by the runtime. Use this method to add services to the container.
- publicvoidConfigureServices(IServiceCollection services)
- {
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env,IApplicationLifetime appLifeTime)
- {
- if(env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- app.UseMvc();
- string ip =Configuration["ip"]??"127.0.0.1";
- string port =Configuration["port"]??"5000";
- string serviceName ="MsgService";
- ServiceEntity serviceEntity =newServiceEntity
- {
- IP = ip,
- Port=Convert.ToInt32(port),
- ServiceName= serviceName,
- ConsulIP="10.248.37.110",
- ConsulPort="8500"
- };
- app.RegisterConsul(appLifeTime, serviceEntity);
- }
- }
AppBuilderExtensions:
- publicstaticclassAppBuilderExtensions
- {
- publicstaticIApplicationBuilderRegisterConsul(thisIApplicationBuilder app,
- IApplicationLifetime lifetime,
- ServiceEntity serviceEntity)
- {
- var consulClient =newConsulClient(x => x.Address=newUri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//请求注册的 Consul 地址
- var httpCheck =newAgentServiceCheck()
- {
- DeregisterCriticalServiceAfter=TimeSpan.FromSeconds(5),//服务启动多久后注册
- Interval=TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔
- HTTP = $"http://{serviceEntity.IP}:{serviceEntity.Port}/api/health",//健康检查地址
- Timeout=TimeSpan.FromSeconds(5)
- };
- // Register service with consul
- var registration =newAgentServiceRegistration()
- {
- Checks=new[]{ httpCheck },
- ID =Guid.NewGuid().ToString(),
- Name= serviceEntity.ServiceName,
- Address= serviceEntity.IP,
- Port= serviceEntity.Port,
- Tags=new[]{ $"urlprefix-/{serviceEntity.ServiceName}"}//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
- };
- consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
- lifetime.ApplicationStopping.Register(()=>
- {
- consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
- });
- return app;
- }
- }
- publicclassServiceEntity
- {
- public string ServiceName{ get;set;}
- public string ConsulIP{ get;set;}
- public string ConsulPort{ get;set;}
- public string IP { get;set;}
- publicintPort{ get;set;}
- }
HealthController:
- [Produces("application/json")]
- [Route("api/Health")]
- public class HealthController : Controller
- {
- [HttpGet]
- public IActionResult Get()
- {
- Console.WriteLine("健康检查" + DateTime.Now);
- return Content("ok");
- }
- }
============ 欢迎各位老板打赏~ ===========
与本文相关的文章
- · .NETCORE 依赖注入服务生命周期
- · .netcore docker 使用 UseUrls 绑定端口时无法访问
- · docker单节点启动consul
- · [转].NET Core开源API网关 – Ocelot中文文档
- · API网关ocelot特性之聚合
- · 使用Ocelot做网关
- · .NET Core微服务之基于Ocelot实现API网关服务
- · consul+nginx完成集群服务动态发现和健康检查
- · Consul 入门教程
- · .netcore获取客户端电脑名和IP
- · 在IIS7上部署你的ASP.NET Core 2项目
- · nginx+keepalive负载均衡高可用