初探.Net Core API 網(wǎng)關(guān)Ocelot(一)

一、介紹

Ocelot 是基于.NetCore實(shí)現(xiàn)的開(kāi)源的API網(wǎng)關(guān),支持IdentityServer認(rèn)證。Ocelot具有路由、請(qǐng)求聚合、服務(wù)發(fā)現(xiàn)、認(rèn)證、鑒權(quán)、限流熔斷等功能,并內(nèi)置了負(fù)載均衡器與Service Fabric、Butterfly Tracing集成。

Ocelot本質(zhì)是由一系列特定順序的.Net Core Middleware組成的一個(gè)管道。Ocelot接收到請(qǐng)求之后,用request bulider來(lái)創(chuàng)建一個(gè)HttpRequestMessage對(duì)象,該對(duì)象根據(jù)配置將請(qǐng)求下發(fā)給下游指定的服務(wù)器進(jìn)行請(qǐng)求處理。下游服務(wù)返回response之后,一個(gè)middleware將它返回的HttpResponseMessage映射到HttpResponse,再轉(zhuǎn)發(fā)給客戶端。

二、如何搭建一個(gè)Ocelot項(xiàng)目

新建一個(gè).net core 項(xiàng)目。我的環(huán)境是:vs2017,.net core 2.1,Ocelot 8.0。

NuGet安裝Ocelot


image.png

添加完項(xiàng)目之后添加ocelot.json配置文件

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/values", // 下游游請(qǐng)求模板
      "DownstreamScheme": "http", //下游服務(wù) schema
      "UpstreamPathTemplate": "/api/values", // 上游請(qǐng)求模板
      "UpstreamHttpMethod": [ "Get" ], // 上游請(qǐng)求http方法
      //下游服務(wù)的地址,如果使用LoadBalancer的話這里可以填多項(xiàng)
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8802
        }
      ],
      //LeastConnection – 將請(qǐng)求發(fā)往最空閑的那個(gè)服務(wù)器
      //"RoundRobin""輪流發(fā)送"
      //"NoLoadBalance" "總是發(fā)往第一個(gè)請(qǐng)求或者是服務(wù)發(fā)現(xiàn)",
      "LoadBalancer": "LeastConnection",
      //熔斷配置
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, //允許的異常請(qǐng)求數(shù)
        "DurationOfBreak": 10, //熔斷的時(shí)間,單位為秒
        "TimeoutValue": 5000 //如果下游請(qǐng)求的處理時(shí)間超過(guò)多少則將請(qǐng)求設(shè)置為超時(shí)
      },
      //緩存配置
      "FileCacheOptions": {
        "TtlSeconds": 10,
        "Region": "somename" //是對(duì)緩存進(jìn)行的一個(gè)分區(qū)
      },
      "HttpHandlerOptions": {
        "AllowAutoRedirect": false,
        "UseCookieContainer": false
      },
      //配置服務(wù)認(rèn)證
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "",
        "AllowedScopes": []
      }
    },
    {
      "DownstreamPathTemplate": "/api/product",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/api/product",
      "UpstreamHttpMethod": [ "Get" ],
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8801
        }
      ],
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3,
        "DurationOfBreak": 10,
        "TimeoutValue": 5000
      },
      "AuthenticationOptions": {

      }
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/admin"
  }
}

將配置文件加入Configuration

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((hostcontext, bulid) => {
                     bulid.SetBasePath(hostcontext.HostingEnvironment.ContentRootPath)
                     .AddJsonFile("ocelot.json");
                 })
                 .UseKestrel()
                .UseIISIntegration()
                .UseStartup<Startup>();
    }

添加依賴注入

       public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot();
        }

添加Ocelot中間件

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseOcelot().Wait();
    }

添加兩個(gè)下游api服務(wù),對(duì)應(yīng)ocelot.json配置的下游服務(wù)

image.png

設(shè)置APIProductService端口為8801APIUserServiec端口為8802APIGateway端口為5000,設(shè)置方式如圖所示:

image.png

啟動(dòng)項(xiàng)目設(shè)置為啟動(dòng)多個(gè)項(xiàng)目


image.png

啟動(dòng)項(xiàng)目

image.png

請(qǐng)求結(jié)果如下


image.png

image.png

image.png

image.png

http://localhost:5000/api/values請(qǐng)求轉(zhuǎn)發(fā)給了下游服務(wù)APIUserServiec處理

image.png

將請(qǐng)求 http://localhost:5000/api/product 轉(zhuǎn)發(fā)給了APIProductService服務(wù)進(jìn)行處理

三、參考

[1] .NET Core開(kāi)源API網(wǎng)關(guān) – Ocelot中文文檔

[2] Ocelot GitHub

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 1、通過(guò)CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明AGI閱讀 16,003評(píng)論 3 119
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,868評(píng)論 18 139
  • 能罵你的師父..都是好師父! 修行能否成功,心量大小是關(guān)鍵。心量太小的人是沒(méi)法承載大法的,所以各位菩薩們要學(xué)會(huì)尊重...
    小茉姐姐閱讀 508評(píng)論 0 0
  • 我的弟弟,又調(diào)皮,又聰明。 我的弟弟今年9歲,是一名小學(xué)三年級(jí)的小學(xué)生。他是一個(gè)既聰明又可愛(ài)的小男孩,他長(zhǎng)著一雙水...
    幸福女孩_d33a閱讀 375評(píng)論 0 0
  • 堂哥說(shuō)春節(jié)星巴克能營(yíng)業(yè)?我說(shuō):地球不爆炸,它們不放假,宇宙不重啟,它們不休息,風(fēng)里雨里節(jié)日里,都在等著你,一年無(wú)四...
    李蓉LiRong閱讀 87評(píng)論 0 0