zoukankan      html  css  js  c++  java
  • Ocelot学习笔记

      最近因工作需要,开始学习Ocelot。首先简单介绍一下,Ocelot是一个基于.net core的开源webapi 服务网关项目,目前已经支持了IdentityServer认证。根据 作者介绍,Ocelot本质上是一堆中间件的集合,当HttpRequest请求到达后由一堆中间件进行处理,处理完毕,请求根据配置转发给下游服务。然后接受下游服务的返回信息在转发给客户端,详细信息请参考作者给出的文档。

      GitHub地址:https://github.com/TomPallister/Ocelot

      先简单介绍下,如何搭建一个Ocelot项目。

      首先,新建一个基于.net core的webapi项目, core版本要高于或等于1.1,因为目前Ocelot是基于.net core1.1

      然后可以通过nuget安装Ocelot  

    Install-Package Ocelot

      至此,项目搭建完毕。下面,在项目中添加 configuration.json 配置文件。Ocelot主要功能都是通过配置项来实现的。首先,我们来实现最简单的服务转发功能。配置文件中有两个配置项,一个是ReRoutes主要的服务路由配置,都配置在此配置项中。一个GlobalConfiguration,全局配置项,一些可应用与全局的配置可放在此配置项中。

      

    "ReRoutes": [
        {
          "DownstreamPathTemplate": "/api/values",
          "DownstreamScheme": "http",
          "DownstreamPort": 8052,
          "DownstreamHost": "localhost",
          "UpstreamPathTemplate": "/api/values",
          "UpstreamHttpMethod": [ "Get" ],
          "QoSOptions": {
            "ExceptionsAllowedBeforeBreaking": 3,
            "DurationOfBreak": 10,
            "TimeoutValue": 5000
          }
        },
        {
          "DownstreamPathTemplate": "/api/product",
          "DownstreamScheme": "http",
          "DownstreamPort": 8053,
          "DownstreamHost": "localhost",
          "UpstreamPathTemplate": "/api/product",
          "UpstreamHttpMethod": [ "Get" ],
          "QoSOptions": {
            "ExceptionsAllowedBeforeBreaking": 3,
            "DurationOfBreak": 10,
            "TimeoutValue": 5000
          }
        }
      ],
      "GlobalConfiguration": {
      }

      配置项完毕后,现在需要修改Startup中的代码

      

      将刚新建的json文件,添加到系统配置项中。然后简单修改一下ConfigureServices和Configure,主要就是将Ocelot作为中间件注册。当然你可以按照自己的需求,做更多的扩展。

      

        Program.cs 类文件代码

       

        至此,全部工作已经完成。然后我们新建两个api服务,对应configuration.json文件中的下游服务。

        

        然后依次启动 apinoe,apitwo,和ServcesGateWay,即可看到结果

        

        

      

  • 相关阅读:
    Parameter Binding in ASP.NET Web API
    Which HTTP methods match up to which CRUD methods?
    ErrorHandling in asp.net web api
    HttpStatusCode
    Autofac Getting Started(默认的构造函数注入)
    Autofac Controlling Scope and Lifetime
    luvit 被忽视的lua 高性能框架(仿nodejs)
    undefined与null的区别
    VsCode中使用Emmet神器快速编写HTML代码
    字符串匹配---KMP算法
  • 原文地址:https://www.cnblogs.com/dandan123/p/7447372.html
Copyright © 2011-2022 走看看