副标题#e#
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": "http://www.jb51.net/",
  //负载均衡类型:轮询
  "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项目分别新建两个GET请求方法,代码分别如下:
//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";
 }
}
通过dotnet run命令启动APIGateway项目(网关层)
dotnet run --project APIGateway项目路径\APIGateway.csproj
通过dotnet run命令启动APIServicesA项目
dotnet run --project APIGateway项目路径\APIGateway.csproj
通过dotnet run命令启动APIServicesB项目
dotnet run --project APIServicesB项目路径\APIServicesB.csproj
通过浏览器查看轮询分发给下游服务返回的结果:
负载均衡轮询分发下游服务成功。
4.自定义负载均衡
Ocelot支持自定义负载均衡的方法。自定义负载均衡的类需要继承ILoadBalancer接口类,下面我们定义一个简单的负载均衡循环输出下游服务的示例:
public class CustomLoadBalancer : ILoadBalancer
{
 private readonly Func<Task<List<Service>>> _services;
 private readonly object _lock = new object();
 private int _last;
public CustomLoadBalancer(Func<Task<List<Service>>> services)
 {
  _services = services;
 }
 public async Task<Response<ServiceHostAndPort>> Lease(HttpContext httpContext)
 {
  var services = await _services();
  lock (_lock)
  {
if (_last >= services.Count)
{
_last = 0;
}
var next = services[_last];
_last++;
return new OkResponse<ServiceHostAndPort>(next.HostAndPort);
  }
 }
 public void Release(ServiceHostAndPort hostAndPort)
 {
 }
}
在Ocelot中注册此类:
#p#副标题#e#
Func<IServiceProvider, DownstreamRoute, IServiceDiscoveryProvider, CustomLoadBalancer> loadBalancerFactoryFunc =
(serviceProvider, Route, serviceDiscoveryProvider) => new CustomLoadBalancer(serviceDiscoveryProvider.Get);
s.AddOcelot().AddCustomLoadBalancer(loadBalancerFactoryFunc);
最后在路由的LoadBalancerOptions配置选项上修改为CustomLoadBalancer自定义负载均衡类名:
"LoadBalancerOptions": {
 "Type": "CustomLoadBalancer"
}
运行项目调试查看结果:
第一次请求时候分发到APIServicesA项目。
第二次请求时候分发到APIServicesB项目。