.net core后端webapi注册到consul,并通过网关访问

步骤1:為項目添加consul依賴

步驟2:在項目中配置consul,具體如下

配置文件中添加如下

"Service": {

"Name": "homepage",

"IP": "172.17.0.12",

"Port": "8300"

},

"Consul": {

"IP": "172.17.0.12",

"Port": "8500"

}

補全startup.cs中的如下方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)

{

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

app.UseCors(x => x

.AllowAnyOrigin()

.AllowAnyMethod()

.AllowAnyHeader()

.AllowCredentials());

#region register this service

ConsulService consulService = new ConsulService()

{

IP = Configuration["Consul:IP"],

Port = Convert.ToInt32(Configuration["Consul:Port"])

};

HealthService healthService = new HealthService()

{

IP = Configuration["Service:IP"],

Port = Convert.ToInt32(Configuration["Service:Port"]),

Name = Configuration["Service:Name"],

};

app.RegisterConsul(lifetime, healthService, consulService);

#endregion

app.UseMvc();

}

添加三個類:

consul注冊類:

using Consul;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Options;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace MaskBackground.Extensions

{

public static class ConsulBuilderExtensions

{

// 服务注册

public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, HealthService healthService, ConsulService consulService)

{

var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{consulService.IP}:{consulService.Port}"));//请求注册的 Consul 地址

var httpCheck = new AgentServiceCheck()

{

DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册

Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔

//HTTP = "http://61.174.171.58:5556/api/health/status",

HTTP = $"http://{healthService.IP}:{healthService.Port}/api/health/status",//健康检查地址

Timeout = TimeSpan.FromSeconds(5)

};

// Register service with consul

var registration = new AgentServiceRegistration()

{

Checks = new[] { httpCheck },

ID = healthService.Name + "_" + healthService.Port,

Name = healthService.Name,

Address = healthService.IP,

Port = healthService.Port,

Tags = new[] { $"urlprefix-/{healthService.Name}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别

};

consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)

lifetime.ApplicationStopping.Register(() =>

{

consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册

});

return app;

}

}

}

參數類:

namespace MaskBackground.Extensions

{

public class ConsulService

{

public string IP { get; set; }

public int Port { get; set; }

}

}

namespace MaskBackground.Extensions

{

public class HealthService

{

public string Name { get; set; }

public string IP { get; set; }

public int Port { get; set; }

}

}

心跳檢測方法

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

namespace HomeBg.Controllers

{

[Route("api/[controller]")]

[ApiController]

public class HealthController : ControllerBase

{

[AllowAnonymous]

[HttpGet("status")]

public IActionResult Status() => Ok(new {Message = $"OK",DateTime = DateTime.Now});

}

}

步驟3:在項目主配置文件中配置網關

"ReRouteOptions": {

"DownstreamPathTemplate": "/api/{url}",

"UpstreamPathTemplate": "/api/homepage/{url}",

"ServiceName": "homepage",

"UseServiceDiscovery": true,

"DownstreamScheme": "http",

"UpstreamHttpMethod": [ "Get", "Post" ],

"LoadBalancer": "LeastConnection",

"ReRouteIsCaseSensitive": false,

"Priority": 9

}

步驟4:在consul中建立網關鍵值對

reroutes-後面的為注冊到consul的服務名稱。寫入如下配置。

[{"DownstreamPathTemplate":"/api/{url}","DownstreamScheme":"http","UpstreamPathTemplate":"/api/homepage/{url}","UpstreamHttpMethod":["Get","Post"],"ServiceName":"homepage","LoadBalancer":"LeastConnection","UseServiceDiscovery":true,"ReRouteIsCaseSensitive":false,"Priority":9}]

步驟5:重啓網關

猜你喜欢

转载自blog.csdn.net/malingyu/article/details/105964766