代码改变世界

.net core使用ocelot---第六篇 负载均衡

2019-08-08 15:42  一截生长  阅读(1902)  评论(0编辑  收藏  举报

简介

  .net core使用ocelot---第一篇 简单使用 
  .net core使用ocelot---第二篇 身份验证 
  .net core使用ocelot---第三篇 日志记录 
  .net core使用ocelot---第四篇 限流熔断 
  .net core使用ocelot---第五篇 服务质量 

         本文介绍Ocelot的负载均衡模块。

什么是负载均衡

         负载平衡可改善跨多个计算资源(例如计算机,计算机群集,网络链接,中央处理单元或磁盘驱动器)的工作负载分布。 负载平衡旨在优化资源使用,最大化吞吐量,最小化响应时间,并避免任何单个资源的过载。

         对于我们的API服务,Ocelot的负载均衡是监听外部客户端访问服务的软件程序。

准备

         我们需要创建三个项目并确保他们能够正常运行。

注意

         我们使用的两个API服务和第一个几乎一样,便于更快的进入状态。

         在APIServicesA项目中,返回“From APIServices”

[HttpGet]  
public string Get()  
{  
    return "From APIServiceA";  
}   

  在APIServicesB项目中,返回“From APIServiceB”

[HttpGet]  
public string Get()  
{  
    return "From APIServiceB";  
}    

配置负载均衡

         我们需要注意DownstreamHostAndPorts和LoadBalancer节点

         DownstreamHostAndPorts是一个包含所有服务主机和端口的数组,在我们本文的例子中包括APIServiceA和APIServiceB.

         LoadBalancer节点值是一个指明负载均衡算法的字符串。

         目前,Ocelot支持两种负载均衡算法,一个是RoundRobin(循环),一个是LeastConnection(最少访问)

         下面是一个配置负载均衡的示例

{  
  "DownstreamPathTemplate": "/api/values",  
  "DownstreamScheme": "http",  
  "DownstreamHostAndPorts": [  
    {  
      "Host": "localhost",  
      "Port": 9001  
    },  
    {  
      "Host": "localhost",  
      "Port": 9002  
    }  
  ],  
  "UpstreamPathTemplate": "/",  
  "LoadBalancer": "RoundRobin",  
  //"LoadBalancer": "LeastConnection",  
  "UpstreamHttpMethod": [ "Get" ]  
}    
//others.....  

  上面配置的意思是说当我们访问http://localhost:9000/,我们会根据RoundRobin(循环)负载均衡策略,在http://localhost:9001/api/values 或者 http://localhost:9002/api/values中返回我们的结果。

  我们演示一下

  正如你看到的,返回值在From APIServiceB 和 From APIServiceA之间切换,证明我们的负载均衡起作用了。Ocelot将客户端请求传递到下游服务。

  源码在此

  网盘链接:https://pan.baidu.com/s/17sqfGcYx8yEHRL_LwKAUlA
  提取码:p3d0

总结

         本文简单介绍了Ocelot的负载均衡模块,它还有服务发现的功能,具体下文讲解。