ASP.NET Core OceLot 網關


 

1、OceLot中間件介紹

  在傳統的BS應用中,隨着業務需求的快速發展變化,需求不斷增長,迫切需要一種更加快速高效的軟件交付方式。微服務可以彌補單體應用不足,是一種更加快速高效軟件架構風格。單體應用被分解成多個更小的服務,每個服務有自己的獨立模塊,單獨部署,然后共同組成一個應用程序。把范圍限定到單個獨立業務模塊功能。分布式部署在各台服務器上。

  而Ocelot開發的目標就是使用.NET運行面向微服務/服務的架構,要達到這個目標需要一個統的系統入口點(我們統稱為API網關),同時需要與IdentityServer或相關的驗證服務進行集成。

  Ocelot同時是一系列按特定順序排列的中間件。

  包括(IdentityServer,Consul,Butterfly)等等。

  Ocelot將HttpRequest對象操作到其配置指定的狀態,直到它到達請求構建器中間件,在該中間件中它創建HttpRequestMessage對象,該對象用於向下游服務發出請求。發出請求的中間件是Ocelot管道中的最后一件事。它不會調用下一個中間件。下游服務的響應存儲在每個請求范圍的存儲庫中,並在請求返回Ocelot管道時進行檢索。有一個中間件將HttpResponseMessage映射到HttpResponse對象並返回給客戶端。

  以下是部署Ocelot時使用的結構圖:

 

 

 

  與IdentityServer4的集成:

 

 

 

 

 

  與Consul的集成:

 

 

 

  從上面基本的介紹可以得出一個結論,OceLot微服務網關類似於經典設計模式的Façade模式,它將底層的復雜細節進行屏蔽,對外提供簡單而統一的調用方式,通常使用HTTP的RESTful API服務。此時,對於客戶端而言,可以是PC端網頁,也可以是移動設備,客戶端通過HTTP方式調用OceLot網關。

 

2、整體設計

       看了前面的基於OceLot微服務的基礎介紹,發現OceLot已提供了足夠強大的功能及擴展能力,而我們只需要進行集成,對就是集成(我們不生產水,我們只是大自然的搬運工),如下圖:

 

 

 

    如圖,我們采用了Nginx作為入口的高可用及負載均衡,通過API網關作為具體二次轉發接入的統一入口,先向IdentityService進行Login以進行驗證並獲取Token,在IdentityService的驗證過程中會訪問數據庫以驗證。接着再通過Consul服務器獲取服務的所在服務器,最后再帶上Token通過API網關去訪問具體的服務A、B、C。這里我們的IdentityService基於IdentityServer4開發,它具有統一登錄驗證和授權的功能。

  而API網關的模塊組件圖大致如下圖:

 

 

 

3、Nginx負載均衡

       點擊進入:https://www.cnblogs.com/littlewrong/p/9491901.html

 

 

4、OceLot網關服務

4.1、路由

  Ocelot的主要功能是接管進入的http請求並把它們轉發給下游服務。目前是以另一個http請求的形式(將來可能是任何傳輸機制)。

      

捕獲所有

  Ocelot的路由還支持捕獲所有樣式的路由,用戶可以指定他們想要匹配所有流量。如果你像下面那樣設置你的配置,請求將被直接代理(它不一定叫url,任何占位符名稱都可以)。

{

    "DownstreamPathTemplate": "/{url}",

    "DownstreamScheme": "https",

    "DownstreamHostAndPorts": [

            {

                "Host": "localhost",

                "Port": 80,

            }

        ],

    "UpstreamPathTemplate": "/{url}",

    "UpstreamHttpMethod": [ "Get" ]

}

該捕獲所有的優先級低於其他任何ReRoute。 如果你的配置中還有下面的ReRoute,那么Ocelot會在捕獲所有配置之前先匹配它。

{
    "DownstreamPathTemplate": "/",
    "DownstreamScheme": "https",
    "DownstreamHostAndPorts": [
            {
                "Host": "10.0.10.1",
                "Port": 80,
            }
        ],
    "UpstreamPathTemplate": "/",
    "UpstreamHttpMethod": [ "Get" ]
}

上游主機

此功能允許您基於上游主機進行ReRoutes。 這是通過查看客戶端使用的主機頭來工作,然后將其用作識別ReRoute的信息的一部分。

為了使用這個功能,在你的配置中加上如下配置。

{
    "DownstreamPathTemplate": "/",
    "DownstreamScheme": "https",
    "DownstreamHostAndPorts": [
            {
                "Host": "10.0.10.1",
                "Port": 80,
            }
        ],
    "UpstreamPathTemplate": "/",
    "UpstreamHttpMethod": [ "Get" ],
    "UpstreamHost": "somedomain.com"
}

上面的ReRoute只會匹配主機頭是somedomain.com的請求。

如果您沒有在ReRoue上設置UpstreamHost,則任何主機頭都可以匹配它。 這基本上是一個捕獲所有功能並保留構建功能時的現有功能。這意味着如果您有兩個相同的ReRoute,其中一個與UpstreamHost是null,另一個有值。 Ocelot會傾向於設定值的那個。

這個功能在問題 216提出要求。

優先級

{
    "Priority": 0
}

0是最低優先級,Ocelot將始終使用0作為/{catchAll}路由條目,並且可以硬編碼。之后,你可以自由設置你想要的任何優先級。

例如你可以這樣:

{
    "UpstreamPathTemplate": "/goods/{catchAll}",
    "Priority": 0
}

還可以:

{
    "UpstreamPathTemplate": "/goods/delete",
    "Priority": 1
}

在上面的例子中,如果您向Ocelot請求/goods/delete,Ocelot將匹配/goods/delete這個ReRoute。不過在不設置優先級以前它會匹配/goods/{catchAll}(因為這是列表中的第一個ReRoute!)。

以上摘自官方的介紹,地址為:https://ocelot.readthedocs.io/en/latest/features/routing.html

最終實現代碼如下:

 

 

 

 

調試時,確認啟動多個項目。

啟動多個項目:

 

 

 

 

 

  進行路由測試:

 

 

 

 

 

 

       通過PostMan測試發現,BookingAPI,及PassengerAPI已通過網關API成功訪問。

 

配置文件解析

{
  "ReRoutes": [ //路由是API網關最基本也是最核心的功能、ReRoutes下就是由多個路由節點組成。
    {
      "DownstreamPathTemplate": "", //下游服務模板
      "UpstreamPathTemplate": "", //上游服務模板
      "UpstreamHttpMethod": [ "Get" ],//上游方法類型Get,Post,Put
      "AddHeadersToRequest": {},//需要在轉發過程中添加到Header的內容
      "FileCacheOptions": { //可以對下游請求結果進行緩存,主要依賴於CacheManager實現
        "TtlSeconds": 10,
        "Region": ""
      },
      "ReRouteIsCaseSensitive": false,//重寫路由是否區分大小寫
      "ServiceName": "",//服務名稱
      "DownstreamScheme": "http",//下游服務schema:http, https
      "DownstreamHostAndPorts": [ //下游服務端口號和地址
        {
          "Host": "localhost",
          "Port": 8001
        }
      ],
      "RateLimitOptions": { //限流設置
        "ClientWhitelist": [], //客戶端白名單
        "EnableRateLimiting": true,//是否啟用限流設置
        "Period": "1s", //每次請求時間間隔
        "PeriodTimespan": 15,//恢復的時間間隔
        "Limit": 1 //請求數量
      },
      "QoSOptions": { //服務質量與熔斷,熔斷的意思是停止將請求轉發到下游服務。當下游服務已經出現故障的時候再請求也是無功而返,
      並且增加下游服務器和API網關的負擔,這個功能是用的Polly來實現的,我們只需要為路由做一些簡單配置即可
        "ExceptionsAllowedBeforeBreaking": 0, //允許多少個異常請求
        "DurationOfBreak": 0, //熔斷的時間,單位為秒
        "TimeoutValue": 0 //如果下游請求的處理時間超過多少則自如將請求設置為超時
      }
    }
  ],
  "UseServiceDiscovery": false,//是否啟用服務發現
  "Aggregates": [ //請求聚合
    {
      "ReRouteKeys": [ //設置需要聚合的路由key
        "booking",
        "passenger"
      ],
      "UpstreamPathTemplate": "/api/getbookingpassengerinfo" //暴露給外部的聚合請求路徑
    },
  "GlobalConfiguration": { //全局配置節點
    "BaseUrl": "https://localhost:5000" //網關基地址
  }
}
{
    "DownstreamPathTemplate": "/api/posts/{postId}",
    "DownstreamScheme": "https",
    "DownstreamHostAndPorts": [
            {
                "Host": "10.0.1.10",
                "Port": 5000,
            },
            {
                "Host": "10.0.1.11",
                "Port": 5000,
            }
        ],
    "UpstreamPathTemplate": "/posts/{postId}",
    "LoadBalancer": "LeastConnection",
    "UpstreamHttpMethod": [ "Put", "Delete" ]
}

萬能模板

如果不希望對請求做任何的處理,則可以使用下面的萬能模板:(萬能模板的優先級最低,只要有其它的路由模板,其它的路由模板則會優先生效)

{
    "DownstreamPathTemplate": "/{url}",
    "DownstreamScheme": "https",
    "DownstreamHostAndPorts": [
            {
                "Host": "localhost",
                "Port": 80,
            }
        ],
    "UpstreamPathTemplate": "/{url}",
    "UpstreamHttpMethod": [ "Get" ]
}

Prioirty優先級

對多個產生沖突的路由設置優化級

{
    "UpstreamPathTemplate": "/goods/{catchAll}"
    "Priority": 0
}
{
    "UpstreamPathTemplate": "/goods/delete"
    "Priority": 1
}

請求聚合

可以通過gateway將客戶端的多個請求聚合然后將結果一次返回到客戶端去,此時我們需要給每個模板指定一個key

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/booking",
      "UpstreamPathTemplate": "/api/getbooking",
      "UpstreamHttpMethod": [ "Get" ],
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8001
        }
      ],
      "Key": "booking"
    },
    {
      "DownstreamPathTemplate": "/api/passenger",
      "UpstreamPathTemplate": "/api/getpassenger",
      "UpstreamHttpMethod": [ "Get" ],
      "ReRouteIsCaseSensitive": false,
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8002
        }
      ],
      "Key": "passenger"
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:5000"
  },
  "Aggregates": [
    {
      "ReRouteKeys": [
        "booking",
        "passenger"
      ],
      "UpstreamPathTemplate": "/api/getbookingpassengerinfo"
    }
  ]
}

需要注意的是:

  1. 聚合服務目前只支持返回json
  2. 目前只支持Get方式請求下游服務
  3. 任何下游的response header並會被丟棄
  4. 如果下游服務返回404,聚合服務只是這個key的value為空,它不會返回404

  有沒有覺得這里的聚合很類似於GraphQL的功能,但實際上在Ocelot中並不打算實現GraphQL的功能,因為畢竟Ocelot的主要職責是實現網關的功能,聚合只是其中的一個feature,GraphQL提供了一個庫 graphql-dotnet ,我們可以用它來完成需要的功能,而在Ocelot中實現類似認證,授權等這樣它擅長的事情:

{
    "ReRoutes": [
        {
            "DownstreamPathTemplate": "/graphql",
            "DownstreamScheme": "http",
            "DownstreamHostAndPorts": [
              {
                "Host": "yourgraphqlhost.com",
                "Port": 80
              }
            ],
            "UpstreamPathTemplate": "/graphql",
            "DelegatingHandlers": [
                "GraphQlDelegatingHandler"
            ]
        }
    ]
  }

  在此感謝KenWang007 https://github.com/KenWang007/OcelotDemo 示例,查了很久的資料,最終通過上面的示例調試成功。

  最后,github 有個 https://github.com/dbarkwell/Ocelot.ConfigEditor,這個項目實現了asp.net core mvc 的在線編輯路由。

 

4.2、API安全認證(OceLot+IdentityServer4)

       IdentityServer4的介紹博客園上已經有非常多了,

       點擊打開:https://www.cnblogs.com/jaycewu/p/7791102.html 可以看一下。

       這里主要介強OceLot集成需要進行改動的地方。

  新增加IdentityService服務API

       參照https://www.cnblogs.com/jaycewu/p/7791102.html

       實現后IdentityService代碼如下:

 

 

 

Startup.cs調整

 

 

 

configuration.json網關配置文件增加Token的獲取地址

{

      "DownstreamPathTemplate": "/connect/token",

      "UpstreamPathTemplate": "/api/connect/token",

      "UpstreamHttpMethod": [ "Post" ],

      "ReRouteIsCaseSensitive": false,

      "DownstreamScheme": "http",

      "DownstreamHostAndPorts": [

        {

          "Host": "localhost",

          "Port": 5001

        }

      ],

      "Key": "IdentityService",

      "RateLimitOptions": {

        "ClientWhitelist": [],

        "EnableRateLimiting": true,

        "Period": "1s",

        "PeriodTimespan": 15,

        "Limit": 1

      }

},

{

      "DownstreamPathTemplate": "/api/passenger",

      "UpstreamPathTemplate": "/api/passenger",

      "UpstreamHttpMethod": [ "Get" ],

      "ReRouteIsCaseSensitive": false,

      "DownstreamScheme": "http",

 

      "ServiceName": "API002",

      "LoadBalancer": "NoLoadBalancer",

      "UseServiceDiscovery": true,

 

      "Key": "passenger",

      "AuthenticationOptions": {

        "AuthenticationProviderKey": "Bearer",

        "AllowScopes": [ "TWAPI" ]

      }

    },

測試

       啟動程序

 

 

 

       未獲取Token的情況下:

 

 

 

  獲取Token:

 

 

 

  帶上Token進行訪問:

 

 

   通過調用發現,返回的結果和預期一樣,調用成功。

 

4.3、服務注冊及發現(OceLot+Consul)

       安裝Consul就不介紹,可以參考:https://www.cnblogs.com/axzxs2001/p/8487521.html 自行調試,按照上面的寫法需要非常注意的一點是OceLot9.X版本以下是OK的,最新版本的需要進行調整幾個地方:

  安裝OceLot.Provider.Consul包

    Install-Package Ocelot.Provider.Consul

  Startup.cs修改

 

 

  configuration.json調整

 

 

 

  官方參考:https://ocelot.readthedocs.io/en/latest/features/servicediscovery.html,按照官方的調整后,調試通過

  測試

  啟動程序及Consul

 

 

 

 

  調用:

 

 

 

  我們發現,OceLot已通過Consul調用成功。

 

4.4、服務質量與熔斷

  熔斷的意思是停止將請求轉發到下游服務。當下游服務已經出現故障的時候再請求也是功而返,並且增加下游服務器和API網關的負擔。這個功能是用的Pollly來實現的,我們只需要為路由做一些簡單配置即可

  "QoSOptions": {

      "ExceptionsAllowedBeforeBreaking":3,

      "DurationOfBreak":5,

      "TimeoutValue":5000

  }

  ExceptionsAllowedBeforeBreaking 允許多少個異常請求

  DurationOfBreak 熔斷的時間,單位為秒

  TimeoutValue 如果下游請求的處理時間超過多少則自如將請求設置為超時。

 

4.5、分流控制

對請求進行限流可以防止下游服務器因為訪問過載而崩潰,這個功能就是我們的張善友添加進去的。非常優雅的實現,我們只需要在路由下加一些簡單的配置即可以完成。

"RateLimitOptions": {

    "ClientWhitelist": [],

    "EnableRateLimiting": true,

    "Period": "1s",

    "PeriodTimespan": 1,

    "Limit": 1

}

ClientWihteList 白名單

EnableRateLimiting 是否啟用限流

Period 統計時間段:1s, 5m, 1h, 1d

PeroidTimeSpan 多少秒之后客戶端可以重試

Limit 在統計時間段內允許的最大請求數量

在 GlobalConfiguration下我們還可以進行以下配置

 

"RateLimitOptions": {

  "DisableRateLimitHeaders": false,

  "QuotaExceededMessage": "Customize Tips!",

  "HttpStatusCode": 999,

  "ClientIdHeader" : "Test"

}

Http頭  X-Rate-Limit 和 Retry-After 是否禁用

QuotaExceedMessage 當請求過載被截斷時返回的消息

HttpStatusCode 當請求過載被截斷時返回的http status

ClientIdHeader 用來識別客戶端的請求頭,默認是 ClientId

如圖:

 

  連續點擊幾下后,返回:429 Too Many Requests.

 

4.6、負載均衡

當下游服務有多個結點的時候,我們可以在DownstreamHostAndPorts中進行配置。

{

    "DownstreamPathTemplate": "/api/posts/{postId}",

    "DownstreamScheme": "https",

    "DownstreamHostAndPorts": [

            {

                "Host": "10.0.1.10",

                "Port": 5000,

            },

            {

                "Host": "10.0.1.11",

                "Port": 5000,

            }

        ],

    "UpstreamPathTemplate": "/posts/{postId}",

    "LoadBalancer": "LeastConnection",

    "UpstreamHttpMethod": [ "Put", "Delete" ]

}

LoadBalancer將決定負載均衡的算法

  • LeastConnection – 將請求發往最空閑的那個服務器
  • RoundRobin – 輪流發送
  • NoLoadBalance – 總是發往第一個請求或者是服務發現

在負載均衡這里,我們還可以和Consul結合來使用服務發現,同一個服務和Name配置成相同,則在請求時,會根據LoadBalancer請求的算法進行訪問,如下:

{

    "service": {

        "id": "count1",

        "name": "Count",

        "tags": ["dev"],

        "address": "localhost",

        "port": 5001

    }

}

{

    "service": {

        "id": "count2",

        "name": "Count",

        "tags": ["dev"],

        "address": "localhost",

        "port": 5002

    }

}

 

4.7、Swagger文檔生成

Swagger 是一個規范和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步你可以通過一個文本編輯器來編輯 Swagger 文件,或者你也可以從你的代碼注釋中自動生成。各種工具都可以使用 Swagger 文件來生成互動的 API 文檔。

在集成Swagger的時候,我們同時需要考慮到與IdentityServer的集成,在調試的時候讓Swagger充許進行驗證。

BookingApi  Startup.cs修改

public void ConfigureServices(IServiceCollection services)

        {

            services.AddSwaggerGen(c =>

            {

                c.SwaggerDoc("v1", new Info { Title = "BookingApi", Version = "v1" });

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme

                {

                    Description = "請輸入帶有Bearer的Token",

                    Name = "Authorization",

                    In = "header",

                    Type = "apiKey"

                });

                //Json Token認證方式,此方式為全局添加

                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>

                {

                    { "Bearer", Enumerable.Empty<string>() }

                });

            });

 

            services.AddMvc();

        }

 

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)

        {

            app.UseSwagger();

 

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),

            // specifying the Swagger JSON endpoint.

            app.UseSwaggerUI(c =>

            {

                c.SwaggerEndpoint("/swagger/v1/swagger.json", "BookingApi");

            });

 

            app.UseMvc();

        }

PassengerApi Startup.cs修改

public void ConfigureServices(IServiceCollection services)

        {

           

            services.AddMvc();

 

            services.AddSwaggerGen(c =>

            {

                c.SwaggerDoc("v1", new Info { Title = "PassengerApi", Version = "v1" });

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme

                {

                    Description = "請輸入帶有Bearer的Token",

                    Name = "Authorization",

                    In = "header",

                    Type = "apiKey"

                });

                //Json Token認證方式,此方式為全局添加

                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>

                {

                    { "Bearer", Enumerable.Empty<string>() }

                });

            });

        }

 

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)

        {

            app.UseSwagger();

 

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),

            // specifying the Swagger JSON endpoint.

            app.UseSwaggerUI(c =>

            {

                c.SwaggerEndpoint("/swagger/v1/swagger.json", "PassengerApi");

            });

           

            app.UseMvc();

        }

Tw.ApiGateway Startup.cs修改

public void ConfigureServices(IServiceCollection services)

        {

            services.AddOcelot().AddConsul();

            services.AddMvcCore(option =>

            {

            }).AddAuthorization().AddJsonFormatters();

 

            services.AddAuthentication("Bearer")

                .AddIdentityServerAuthentication(options =>

                {

                    options.Authority = "http://localhost:5001";

                    options.RequireHttpsMetadata = false;

                    options.ApiName = "TWAPI";

                });

 

            services.AddMvc();

            services.AddSwaggerGen(options =>

            {

                options.SwaggerDoc("ApiGateway", new Info { Title = "網關服務", Version = "v1" });

               

            });

        }

 

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)

        {

            var apis = new List<string> { "BookingApi", "PassengerApi" };

            app.UseMvc()

               .UseSwagger()

               .UseSwaggerUI(options =>

               {

                   apis.ForEach(m =>

                   {

                       options.SwaggerEndpoint($"/{m}/swagger.json", m);

                   });

               });

 

            app.UseAuthentication();

            

            app.UseOcelot().Wait();

        }

測試

啟動程序:

查看生成的API:

 

 

 

 

調用:

 

 

 

失敗,加上驗證:

 

 

 

 

 

 

 

最后調用成功。

 

4.8、數據監控 NLOG+Grafana+InfluxDB

數據監控分為2個部分,一是基於Grafana+InfluxDB的計數。二是基於NLOG的日志記錄。

  如圖:

  NLOG的配置:

<?xml version="1.0" encoding="utf-8" ?>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  throwConfigExceptions="true"
  internalLogLevel="info"
  internalLogFile="c:\ApiGatewayLog\NLog-AspNetCore2.txt">

  <!-- the targets to write to -->
  <targets>

  <target xsi:type="File" name="Trace" fileName="c:\ApiGatewayLog\Trace-${shortdate}.log"
  layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

  <target xsi:type="File" name="Debug" fileName="c:\ApiGatewayLog\Debug-${shortdate}.log"
  layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

  <target xsi:type="File" name="Info" fileName="c:\ApiGatewayLog\Info-${shortdate}.log"
  layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

  <target xsi:type="File" name="Warn" fileName="c:\ApiGatewayLog\Warn-${shortdate}.log"
  layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

  <target xsi:type="File" name="Error" fileName="c:\ApiGatewayLog\Error-${shortdate}.log"
  layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

  <target xsi:type="File" name="Fatal" fileName="c:\ApiGatewayLog\Fatal-${shortdate}.log"
  layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

</targets>

<rules>

<logger name="*" minlevel="Trace" writeTo="Trace"/>

<logger name="*" minlevel="Debug" writeTo="Debug"/>

<logger name="*" minlevel="Info" writeTo="Info"/>

<logger name="*" minlevel="Warn" writeTo="Warn" />

<logger name="*" minlevel="Error" writeTo="Error"/>

<logger name="*" minlevel="Fatal" writeTo="Fatal"/>

</rules>
</nlog>

 

Grafana+InfluxDB的安裝教程可在園子里搜一下,比較多,Grafana+InfluxDB安裝完成后,最終效果圖如下:

 

  

 

5、源碼介紹

5.1、源碼結構

       API

              Booking Api 測試用API

              PassengerApi 測試用API

       ApiGateWay

              Tw.ApiGateway OceLot網關

              Tw.IdentityService IdentityServer4服務

       Libraies

              Tw.Core 功能類庫

              Tw.Redis 功能類庫

              Tw.Repository 類庫

              Tw.Service 業務操作庫

       MiddleWare

              Tw.IdentityServer IdentityServer4中間件源碼

              Tw.IdentityServer4.AccessTokenValidation 中間件源碼

              Tw.Ocelot OceLot源碼

              Tw.Ocelot.Provider.Consul 源碼

 

5.2、下載地址

下載地址:https://github.com/littlewrong/ApiGateway

 

6、相關資料

1、https://ocelot.readthedocs.io/en/latest/introduction/bigpicture.html 官網介紹

2、http://www.sohu.com/a/132033560_468635 微服務網關Ocelot

3、https://blog.csdn.net/ai52011/article/details/77645009 Surgin API網關

4、https://github.com/KenWang007/OcelotDemo KenWang007/OcelotDemo

5、https://www.cnblogs.com/jaycewu/p/7791102.html IdentityServer4實現Token認證登錄以及權限控制

6、http://www.cnblogs.com/edisonchou/archive/2018/07/08/9278775.html .NET Core微服務之基於Ocelot+IdentityServer實現統一驗證與授權

7、https://www.cnblogs.com/axzxs2001/p/8487521.html Ocelot + Consul實踐

8、https://www.jianshu.com/p/05a1bf2545a0 .Netcore 2.0 Ocelot Api網關教程

9、https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html .NET Core開源API網關 – Ocelot中文文檔

10、https://www.cnblogs.com/shanyou/p/8413506.html Ocelot 集成Butterfly 實現分布式跟蹤

 

后話:最后把程序搬到了Linux安裝部署,實驗成功。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM