.NET Core微服务二:Ocelot API网关

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

.NET Core微服务二:Ocelot API网关

充钱你会更强   2020-02-03 我要评论

.NET Core微服务一:Consul服务中心

.NET Core微服务二:Ocelot API网关

.NET Core微服务三:polly熔断与降级

 

本文的项目代码,在文章结尾处可以下载。

本文使用的环境:Windows10 64位 + VS 2019 + .NET Core 2.1 + Ocelot 8.0.8

Ocelot 相关地址:

https://github.com/ThreeMammals/Ocelot

https://ocelot.readthedocs.io/en/latest/introduction/gettingstarted.html

 

截至2020.02.03发现:

Ocelot单独使用的时候,用目前最新版14.0.3没什么问题,看“Ocelot的简单使用”这篇文章。

在与Consul配合使用的时候,环境要是.NET Core 2.1 + Ocelot 8.0.8这样组合就正常,

高于这样的版本,要么出现“404”,要么出现“目标拒绝”的错误,又或者其它莫名异常;

并且也有个问题,如果一个服务有多台服务器,那Ocelot的负载均衡只会连接到一台服务器。

或许是我操作的方式不对,反正目前我没有找到解决方法,有知道的大神麻烦告知下。

 

 

承接着“.NET Core微服务一:Consul服务中心”这篇文章,通过cmd运行起“Student”和“Teacher”服务,接下来就是创建网关项目

一、新建webapi项目,命名为“Ocelot_Consul”,去掉HTTPS勾选,不需要Controller,改为控制台方式启动

 

二、打开程序包管理器控制台,执行命令:

Install-Package Ocelot -Version 8.0.8

 

三、在项目根目录下,新建配置文件“ocelot.json”

"LoadBalancer"负载均衡类型:

RoundRobin:轮询机制,循环找到可以用的服务

LeastConnection:最少连接数,跟踪发现现在有最少请求或处理的可用服务

NoLoadBalancer:不使用负载均衡,直接访问第一个发现的可用的服务

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/Default/GetList",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/api/v1/Student/GetList",
      "UpstreamHttpMethod": [ "Get" ],
      "ServiceName": "Student",
      "LoadBalancer": "RoundRobin",
      "UseServiceDiscovery": true
      //  ,
      //"RateLimitOptions": {
      //  "ClientWhitelist": [], //白名单
      //  "EnableRateLimiting": true, //是否限流
      //  "Period": "30s", //指定一个时间
      //  "PeriodTimespan": 10, //多少时间后,可以重新请求。
      //  "Limit": 5 //在Period的指定时间内,最多请求次数
      //}
    },
    {
      "DownstreamPathTemplate": "/api/Default/GetList",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/api/v1/Teacher/GetList",
      "UpstreamHttpMethod": [ "Get" ],
      "ServiceName": "Teacher",
      "LoadBalancer": "RoundRobin",
      "UseServiceDiscovery": true
    }
  ],

  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Host": "127.0.0.1",
      "Port": 8500
    }
  }
}

 

四、在Program.cs的CreateHostBuilder中加入

.ConfigureAppConfiguration(conf => {
    conf.AddJsonFile("ocelot.json", false, true);
})

 

五、找到Startup.cs

在ConfigureServices中加入:

services.AddOcelot();

在Configure中加入:

app.UseOcelot().Wait();

注:较高的Ocelot版本,需要“Ocelot.Provider.Consul”组件,ConfigureServices会不一样:

  services.AddOcelot().AddConsul().AddConfigStoredInConsul();

 

六、通过VS启动“Ocelot_Consul”,通过“ocelot.json”配置的对外的路由

“Student”服务的访问地址为:http://localhost:5000/api/v1/Student/GetList

“Teacher”服务的访问地址为:http://localhost:5000/api/v1/Teacher/GetList

  

 

 

代码:https://files.cnblogs.com/files/shousiji/Ocelot_Consul.rar

 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们