.Net6基于Ocelot搭建网关服务及负载均衡配置
在上一篇.Net6基于IdentityServer4配置服务授权以及策略授权中,配置了服务授权以及策略授权,这篇来搭建基础的网关服务。
网关大家都知道有什么用,就是很多个服务配置统一的入口访问地址。Ocelot有很多操作,比如负载均衡、限流、缓存、熔断
等
这篇就只说基础的配置。
新建一个名为
Ocelot.Server
.Net6的空项目,引用包源Ocelot
添加ocelot.json文件
{
"Routes": [
{
"DownstreamPathTemplate": "/{url}",
"DownstreamScheme": "http",
// 下游服务的Method只能配置一个,不能配置成数组
//"DownstreamHttpMethod": "POST",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
},
{
"Host": "localhost",
"Port": 5002
}
],
"UpstreamPathTemplate": "/api/v1/{url}",
"UpstreamHttpMethod": [
"GET",
"POST"
],
"LoadBalancerOptions": {
"Type": "RoundRobin" // RoundRobin负载均衡
}
}
],
"GlobalConfiguration": {
// 网关服务的访问地址
"BaseUrl": "http://localhost:5000",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
}
UpstreamPathTemplate
为前端或客户端访问的路由
DownstreamPathTemplate
为网关访问实际接口的路由
如上面这个配置,前端或客户端访问的地址则是http://localhost:5000/api/v1/OcelotTest/GetOcelotTest
Program注入 两种都可以
// var config = new ConfigurationBuilder()
// .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
// .Build();
// builder.Services.AddOcelot(config);
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot();
app.UseOcelot().Wait();
新建
Web.API.Test1
,Web.API.Test2
的.Net6项目修改端口号分别为5001、5002
两个项目都添加OcelotTestController
using Microsoft.AspNetCore.Mvc;
namespace Web.API.Test1.Controllers;
[ApiController]
[Route("[controller]")]
public class OcelotTestController : ControllerBase
{
[HttpGet("GetOcelotTest")]
public IActionResult GetOcelotTest()
{
return Ok("DateTime:" + DateTime.Now + "--Port:5001"); // 区分这次请求的是哪个服务
}
}
使用postman
请求
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人