
作者:天津九安特機電工程有限公司 來(lái)源: 天津九安特機電工程有限公司 日期:2026-05-05 09:29:04
這篇文章主要介紹了ASP.NET Core3.1 Ocelot負載均衡的負載實(shí)現,文中通過(guò)示例代碼介紹的均衡非常詳細,對大家的負載學(xué)習或者工作具有一定的參考學(xué)習價(jià)值,需要的均衡朋友們下面隨著(zhù)小編來(lái)一起學(xué)習學(xué)習吧
1.負?載均衡
Ocelot可以在每個(gè)路由的可用下游服務(wù)中實(shí)現負載均衡,這使我們更有效地選擇下游服務(wù)來(lái)處理請求。負載負載均衡類(lèi)型:
LeastConnectio??n:根據服務(wù)正在處理請求量的均衡情況來(lái)決(jue)定哪個(gè)服(′?ω?`)務(wù)來(lái)處理新請求,即將新請求發(fā)送到具有最少現有請求的負載(O_O)服務(wù)去處理。算法狀態(tài)沒(méi)有分布在Ocelot集群中。均衡
RoundRobin:遍歷(′?`*)可用服務(wù)并發(fā)送請求。負載算法狀態(tài)沒(méi)有分布在Ocelot集群中。均衡
NoLoadBalancer:從配置或服務(wù)發(fā)現中獲取第一個(gè)可用服務(wù)來(lái)處理新請求。負載
CookieStickySessions:通過(guò)使用Cookie,均衡確保特定的負(/ω\)載請求能夠被分配到特定的服務(wù)上進(jìn)行處理。
在Ocelot負載?均衡項目示例中,均衡通過(guò)網(wǎng)關(guān)項目的負載路由LoadBalancerOptions選項可以配置負載均衡類(lèi)型:
{
"Routes": [
{
//下游路由服務(wù)地址
"DownstreamPathTemplate": "/api/values",
//下游服務(wù)地址訪(fǎng)問(wèn)協(xié)議類(lèi)型http或者https
"DownstreamSchem??e": "http",
//下游服務(wù)的主(╬?益?)機和端口
"DownstreamHostAndPorts": [
{
"Host": "local??host",
"Port": 9001
},
{
"Host":┐(′ー`)┌ "localhost",
"Port": 900(′ω`)2
}
],
//上游服務(wù)地址,即下游服務(wù)真實(shí)訪(fǎng)問(wèn)地址
"UpstreamPathTemplate": "/",
//負載均衡類(lèi)型:輪詢(xún)
"LoadBalancerOptio┐(′?`)┌ns": {
"Type": "RoundRobin"
},
//上游服務(wù)HTTP請求方式,例如Get、Post
"UpstreamHttpMethod": [ "Get" ]
}
]
}
2.服務(wù)發(fā)現
下面展示??如何使用服務(wù)發(fā)現來(lái)設置路由:
{???
"DownstreamPathTemplate": "/api/posts/{ postId}",
"Downstrヽ(′▽?zhuān)?ノeamScheme": "https",
"Upstre??amPathTemplate": "/posts/{ postId}",
"UpstreamHttpMethod": [ "Put" ],
"ServiceName": "product",
"LoadBalancerOpt(′▽?zhuān)?)ions": {
"Type": "LeastConnection"
}
}
設置此選項后,Ocelot將從服務(wù)發(fā)現提供程序中查找下游主機和端口,并在所有可用服務(wù)中進(jìn)行負載平衡請求。如果您從服務(wù)發(fā)現提供者(領(lǐng)事)中添加和刪除服務(wù),Oc(°ロ°) !elot會(huì )停(°o°)止調用已刪除的服務(wù),并開(kāi)始調用已添加的服務(wù)。后續學(xué)習服務(wù)發(fā)現這塊知識點(diǎn)時(shí)候會(huì )重新(xin)再講解。
3.1APIGateway項目
該項目通過(guò)LoadBalancerOptions配置選項定義服務(wù)負載均衡請求機制,事例項??(′?_?`)目使用的負載均衡類(lèi)型是RoundRobin,在Progra( ?ω?)m添加Ocelot支持代碼如下:
public static IWebHostBuilder CreateWebHostBuilder(string[??] args) =&g??t;
WebHost.CreateDefau??ltBuilder(args)
//.UseStartup<Startup>()
.UseUrls("http://*:90(′▽?zhuān)?)00")
.Configure??App??Configuration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
//添加Ocelot配置文件
.AddJsonFile("configuration.json")
.AddEnvironmentVariables();
})
.ConfigureServices(╬?益?)(s =>
{
//添加Ocelot服務(wù);
s.AddOcelot();
})
.Configure(a =>
{
//使用Ocelot
a.UseOcelot().Wait();
});
3.2APIServicesA和APIServicesB下游服務(wù)項目
APIServicesA和APIServic??esB項ヽ(′ー`)ノ目分別新建兩個(gè)GE??T請求方法,代碼分別如下:
//APIServices??A
[Route("api/[controller]")]
public class ValuesController : Contro(′?`*)ller
{
// GET api/values
[HttpGet]
public string Get()
{
return "From APIServiceA";
}
}
//APIServicesB
[Route("api/[controller]")]ヽ(′?`)ノ
public class ValuesController : Cont??roller
{
// GET api/values
[HttpGet]
public string Get()
{
return "From APIServi??ceB";
}
}
通過(guò)dotnet run命令啟動(dòng)APIGateway項目(網(wǎng)關(guān)層)
dotnet run --project APIGateway項目路徑\APIGateway.csp??roj
dot??net run --pr(?????)oject APIGateway項目路徑\API??Gateway.csproj
通過(guò)dotnet run命令啟動(dòng)APIServicesB項目
dotnet run --project APIServicesB項目路徑\APIServicesB.csproj
通過(guò)瀏覽器查看輪詢(xún)分發(fā)給下游服務(wù)(wu)返回的ヽ(′ー`)ノ結果:
負載均衡輪詢(xún)分發(fā)下游服務(wù)成功。
4.自定義負??載均衡
p??ublic class CustomLoadBalancer : ILoadBalancer
{
pr(╬?益?)ivate readonly="" Func<Task&l??t;List<Serviceヽ(′ー`)ノ>>> _services;
private readonly='readonly' object _lock = new object();
private int _last;
p??ublic CustomLoadBalancer(Func<Task(???)<List<Service>>> services)
{
_services = services;
}
public async Task<Response<ServiceHostAndPort>> Lease(HttpContext httpContext)
{
var services = await _serv??ice??s();
lock (_lock)
{
if (_last >= services.Count)
{
_last = 0;
}
var next = services[_last];
_last++;
return new OkResp(/ω\)onse<ServiceHostAndPort>??;(next.HostAndPort);
}
}
public void Release(ServiceHostAndPort hostAndPort)
{
}
}
在Ocelot中注冊此類(lèi):
Func<IServiceProvider, Downstreヽ(′?`)ノamRoute, IServiceDiscoveryProvidヽ(′?`)ノer, CustomLoa??dBalance(′▽?zhuān)?r> loadBala???ncerFactoryFunc =
(serviceProvider, Route, serviceDiscoveryProvider) => new CustomLoadBalancer(serviceDiscoveryProvider.Get);
s.AddOcelo??t().AddCustomLoadBalancer(loadBalancerFactoryFunc);
最后在路由的LoadBalancerOptions配置?選項上修改為(wei)CustomLoadBalancer自定義負載均衡類(lèi)名:
"LoadBalancerOptions?": {
"Type": "CustomLoadBalancer"
}
運行項目調試查看結果:
從上面結果(guo)來(lái)看,自定義負載(zai)均衡成功。
參考文獻:
Ocelot官網(wǎng)
到此這篇關(guān)于A(yíng)SP.NET Core3.1 Ocelot負載均衡的實(shí)現的文章就介紹到這了,更多相關(guān)ASP.NET Core3.1 Oc(′_`)elot負載均衡內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
來(lái)源:腳本之(zhi)家
鏈接:https://www.jb5??1.net(′?`*)/article/199546.htm