• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

ASP.NET Core3.1 Ocelot负载均衡的实现

c# 搞代码 4年前 (2022-01-09) 8次浏览 已收录 0个评论

1.负载均衡

Ocelot可以在每个路由的可用下游服务中实现负载均衡,这使我们更有效地选择下游服务来处理请求。负载均衡类型:

  • LeastConnection:根据服务正在处理请求量的情况来决定哪个服务来处理新请求,即将新请求发送到具有最少现有请求的服务去处理。算法状态没有分布在Ocelot集群中。
  • RoundRobin:遍历可用服务并发送请求。算法状态没有分布在Ocelot集群中。
  • NoLoadBalancer:从配置或服务发现中获取第一个可用服务来处理新请求。
  • CookieStickySessions:通过使用Cookie,确保特定的请求能够被分配到特定的服务上进行处理。

在Ocelot负载均衡项目示例中,通过网关项目的路由LoadBalancerOptions选项可以配置负载均衡类型:

{
 "Routes": [
 {
  //下游路由服务地址
  "DownstreamPathTemplate": "/api/values",
  //下游服务地址访问协议类型http或者https
  "DownstreamScheme": "http",
  //下游服务的主机和端口
  "DownstreamHostAndPorts": [
  {
   "Host": "localhost",
   "Port": 9001
  },
  {
   "Host": "localhost",
   "Port": 9002
  }
  ],
  //上游服务地址,即下游服务真实访问地址
  "UpstreamPathTemplate": "/",
  //负载均衡类型:轮询
  "LoadBalancerOptions": {
  "Type": "RoundRobin"
  },
  //上游服务HTTP请求方式,例如Get、Post
  "UpstreamHttpMethod": [ "Get" ]
 }
 ]
}

新请求通过上游访问下游服务的时候,Ocelot会根据LoadBalancerOptions负载均衡选项类型来分发到具体下游服务。

2.服务发现

下面展示如何使用服务发现来设置路由:

{
 "DownstreamPathTemplate": "/api/posts/{postId}",
 "DownstreamScheme": "https",
 "UpstreamPathTemplate": "/posts/{postId}",
 "UpstreamHttpMethod": [ "Put" ],
 "ServiceName": "product",
 "LoadBalancerOptions": {
  "Type": "LeastConnection"
 }
}

设置此选项后,Ocelot将从服务发现提供程序中查找下游主机和端口,并在所有可用服务中进行负载平衡请求。如果您从服务发现提供者(领事)中添加和删除服务,Ocelot会停止调用已删除的服务,并开始调用已添加的服务。后续学习服务发现这块知识点时候会重新再讲解。

3.项目演示

3.1APIGateway项目

该项目通过LoadBalancerOptions配置选项定义服务负载均衡请求机制,事例项目使用的负载均衡类型是RoundRobin,在Program添加Ocelot支持代码如下:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
 WebHost.CreateDefaultBuilder(args)
   //.UseStartup<Startup>()
   .UseUrls("http://*:9000")
   .ConfigureAppConfiguration((hostingContext, config) =>
  {
   config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
    //添加Ocelot配置文件
.AddJsonFile("configuration.json")
    .AddEnvironmentVariables();
  })
  .ConfigureServices(s =>
  {
   //添加Ocelot服务;
   s.AddOcelot();
  })
  .Configure(a =>
  {
    //使用Ocelot
   a.UseOcelot().Wait();
  });

3.2APIServicesA和APIServicesB下游服务项目

APIServicesA和APIServicesB项目分别新建两个GE本文来源gaodai#ma#com搞@@代~&码网^T请求方法,代码分别如下:

//APIServicesA
[Route("api/[controller]")]
public class ValuesController : Controller
{
 // GET api/values
 [HttpGet]
 public string Get()
 {
  return "From APIServiceA";
 }
}
//APIServicesB
[Route("api/[controller]")]
public class ValuesController : Controller
{
 // GET api/values
 [HttpGet]
 public string Get()
 {
  return "From APIServiceB";
 }  
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:ASP.NET Core3.1 Ocelot负载均衡的实现

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址