86

Ocelot网关 - 桂素伟

 6 years ago
source link: http://www.cnblogs.com/axzxs2001/p/8005041.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Ocelot网关 - 桂素伟 - 博客园

Ocelot是一个.net core框架下的网关的开源项目,下图是官方给出的基础实现图,即把后台的多个服务统一到网关处,前端应用:桌面端,web端,app端都只用访问网关即可。

 

14888-20171208134842296-1276324683.png

Ocelot的实现原理就是把客户端对网关的请求(Request),按照configuration.json的映射配置,转发给对应的后端http service,然后从后端http service获取响应(Response)后,再返回给客户端。当然有了网关后,我们可以在网关这层去做统一验证,也可以在网关处统一作监控。

接下来做个Demo

新建三个asp.net core web aip项目:

OcelotGateway网关项目,端口是5000

DemoAAPI项目A,端口是5001

DemoBAPI项目B,端口是5002

(注:端口可以在每个项目的Properties下的launchSettings.json中修改,发布后的端口可以在Program.cs中用UseUrls(“http://*:5000”)来修改)

对于OcelotGateway:

引用Ocelot的Nuget包:

视图->其他窗口->程序包管理控制台:Install-Package Ocelot

或项目右键“管理Nuget程序包”,在浏览里查找Ocelot进行安装

在OcelotGateway项目中添加一个configuration.json文件,关把它的属性“复制到输出目录”,设成“始终复制”,内容如下:

{

  "ReRoutes": [

    {

      "DownstreamPathTemplate": "/demoaapi/values",

      "DownstreamScheme": "http",

      "DownstreamPort": 5001,

      "DownstreamHost": "localhost",

      "UpstreamPathTemplate": "/demoaapi/values",

      "UpstreamHttpMethod": [ "Get" ],

      "QoSOptions": {

        "ExceptionsAllowedBeforeBreaking": 3,

        "DurationOfBreak": 10,

        "TimeoutValue": 5000

      },

      "HttpHandlerOptions": {

        "AllowAutoRedirect": false,

        "UseCookieContainer": false

      },

      "AuthenticationOptions": {

        "AuthenticationProviderKey": "",

        "AllowedScopes": []

      }

    },

    {

      "DownstreamPathTemplate": "/demobapi/values",

      "DownstreamScheme": "http",

      "DownstreamPort": 5002,

      "DownstreamHost": "localhost",

      "UpstreamPathTemplate": "/demobapi/values",

      "UpstreamHttpMethod": [ "Get" ],

      "QoSOptions": {

        "ExceptionsAllowedBeforeBreaking": 3,

        "DurationOfBreak": 10,

        "TimeoutValue": 5000

      },

      "HttpHandlerOptions": {

        "AllowAutoRedirect": false,

        "UseCookieContainer": false

      },

      "AuthenticationOptions": {

        "AuthenticationProviderKey": "",

        "AllowedScopes": []

      }

    }

  ]

}

接下来对OcelotGateway的Program.cs进行改造 

ContractedBlock.gifExpandedBlockStart.gif

View Code

同时,修改Startup.cs

ContractedBlock.gifExpandedBlockStart.gif

View Code

为了测试数据好看,我们把DemoAAPI项目和DemoBAPI项目的ValuesController作一下修改:    

ContractedBlock.gifExpandedBlockStart.gif

View Code

最后在解决方案属性->多个启动项目中,把DemoAAPI,DemoBAPI,OcelotGateway都设成启动,开始启动解决方案,效果如下图 

14888-20171208134919156-767442057.png

《基于.net core微服务架构视频》

 http://edu.51cto.com/course/13342.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK