Ocelot之负载均衡
Ocelot之负载均衡
前言
通过上节介绍“Ocelot快速实践”后,了解了Ocelot网关,可以通过访问网关将请求转发到后台的webapi程序里。Ocelot还支持负载均衡的实现,只需配置文件进行修改。Ocelot能通过可用的下游服务对每个Routes进行负载平衡。 这意味着您可以扩展您的下游服务,并且Ocelot可以有效地使用它们。
环境:
VS2022 +.NET5.0 + Ocelot17.0.0.0
1 Ocelot负载均衡
Ocelot是基于 webapi 的网关框架,要使用ocelot来做路由转发和负载均衡,需要创建一个webapi,然后以这个webapi来做gateway。
配置说明
在Reroute节点中添加LoadBalancerOptions,这是负载均衡的配置节点,其中Type属性指定了负载均衡的算法, 它有如下几个值:
l LeastConnection – 将请求发往最空闲的那个服务器
l RoundRobin – 轮流发送
l NoLoadBalance – 总是发往第一个请求(如果配置了服务发现,则总是发往发现的第一个服务地址)
l CookieStickySessions - 使用cookie关联所有相关的请求到制定的服务。
2 项目演示
接下来我们就来验证该功能的实现。
在上节“Ocelot快速实践”项目基础上进行改造,实现的目标是通过Ocelot负载均衡轮流访问接口。项目机构如下:
2.1 修改接口服务
Step1 修改天气预报控制器“WeatherForecastController”,在接口访问时打印IP及端口信息。代码如下:
namespace Yak.Ocelot.Api.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; }
[HttpGet] public IEnumerable<WeatherForecast> Get() { string str = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + Request.HttpContext.Connection.LocalPort; _logger.LogInformation(str); //显示请求的IP及端口 var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } } |
Step2 启动接口,端口号为6000:
dotnet run --urls=http://*:6000 |
Step2 启动接口,端口号为7000:
dotnet run --urls=http://*:7000 |
2.2 修改Ocelot网关配置
配置如下:
{ "Routes": [ { "DownstreamPathTemplate": "/WeatherForecast", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 6000 }, { "Host": "localhost", "Port": 7000 }
], "UpstreamPathTemplate": "/Weather", "UpstreamHttpMethod": [ "Get" ], "LoadBalancerOptions": { "Type": "RoundRobin" }
} ], "GlobalConfiguration": { "BaseUrl": "https://localhost:5000" } } |
2.3 验证
Step1 运行网关项目“Yak.Ocelot.Gateway”。
Step2 通过网关访问天气预报地址:“http://localhost:5000/Weather”获取天气,多调用几次后发现两个后端服务轮流被调用。
3 总结
本节的实践介绍了轮流发送(RoundRobin)配置,后台提供了两个接口服务,很均衡地调用两个服务,使得服务均衡,不偏袒谁。若两个服务分部发布到两台服务器上,服务器的压力也做到了均衡。
4 鸣谢
https://www.cnblogs.com/lcyhjx/p/12687152.html
5 源码
https://github.com/yandaniugithub/NETCore
本文来自博客园,作者:{春光牛牛,yak},转载请注明原文链接:https://www.cnblogs.com/yakniu/p/16155858.html
欢迎各位大佬们评论指正
QQ讨论群:610129902
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异