ApiServer配置
服务项目建立
新建一个 Asp.net core Web Api 项目,取名为 ApiA (ApiB的配置与此相同)
引入 Consul Nuget 包
Consul 注册及健康检查
修改 appsettings.json,添加相关配置节点
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"urls": "http://localhost:6001", //当前服务的网址,根据项目属性中配置的进行修改
"consul_urls": "http://localhost:8500", //Consul服务的地址
"service_id": "1", //当前服务的ID
"service_name": "ApiA" //当前服务的名称ApiA或ApiB
}
添加公共帮助类
新建一个类 PublicHelper.cs,内容如下
public class PublicHelper
{
/// <summary>
/// 向Consule服务注册
/// </summary>
/// <param name="configuration"></param>
public static void RegSerToConsul(IConfiguration configuration)
{
string urls = configuration["urls"].Trim('/'); // 当前服务的网址
string jconsulUrls = configuration["consul_urls"]; // Consul服务的网址
string serviceId = configuration["service_id"]; // 当前服务的ID
string serviceName = configuration["service_name"]; //当前服务的名称
//健康检查连接资料
var client = new ConsulClient(_ => _.Address = new Uri(jconsulUrls));
var checkAgent = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 启动后5秒开始向Consul服务注册
Interval = TimeSpan.FromSeconds(20), // 间隔20秒健康检查一次当前服务是否健康
HTTP = $"{urls}/api/Health", //健康检查的接口
Timeout = TimeSpan.FromSeconds(10) //超时时间
};
string[] urlArr = urls.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
int port = 80;
if (urlArr.Length > 2)
{
port = int.Parse(urlArr[2]);
}
string address = urlArr[1].TrimStart("//".ToArray());
//当前服务的相关连接信息
AgentServiceRegistration registration = new AgentServiceRegistration()
{
Checks = new[] { checkAgent },
ID = $"{serviceName}-{serviceId}",
Name = serviceName,
Address = address,
Port = port
};
client.Agent.ServiceRegister(registration).Wait();
}
}
修改 Startup.cs ,进行服务注册
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//调用公共帮助类的注册方法
PublicHelper.RegSerToConsul(Configuration);
}
添加健康检查接口
新建一个Api控制器,命名HealthConroller
namespace ApiA.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HealthController : ControllerBase
{
public string Get() => "ok";
}
}
添加测试接口
新建一个Api控制器,命名为 UserInfoController
namespace ApiA.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserInfoController : ControllerBase
{
public JsonResult Post()
{
return new JsonResult(new
{
user_no = "AdminA",
user_name = "管理员A",
sex = "男",
tel = "13000000000"
});
}
}
}
至此项目配置完成,已可以通过Ocelot网关进行访问。
验证测试
- 同时启动 OcelotService、ApiA、ApiB,查看Consul-ui http://localhost:8500 是否注册成功
可以看到ApiA和ApiB已注册成功 - 通过Ocelot网关访问ApiA的接口UserInfo
通过上图,可以看到能过Ocelot网关访问ApiA项目的接口UserInfo成功