1. 程式人生 > >微服務三:API閘道器和驗證

微服務三:API閘道器和驗證

簡介

現有微服務的幾點不足:

1> 對於在微服務體系中、和Consul通訊的微服務來講,使用服務名即可訪問。但是對於手機、web端等外部訪問者仍然需要和N多伺服器互動,需要記憶他們的伺服器地址、埠號等。一旦內部發生修改,很麻煩,而且有時候內部伺服器是不希望外界直接訪問的。

2> 各個業務系統的人無法自由的維護自己負責的伺服器;

3> 現有的微服務都是“我家大門常開啟”,沒有做許可權校驗。如果把許可權校驗程式碼寫到每個微服務上,那麼開發工作量太大。(假如一個系統中存在幾十個微服務,每個微服務都有自己的獨立許可權校驗,就太麻煩了)

4> 很難做限流、收費等。(例如:我有一個臺傳送簡訊的微服務,一個使用者每天可以免費傳送5條簡訊,如果想傳送6條簡訊就要收費)
ocelot 中文文件:https://blog.csdn.net/sD7O95O/article/details/79623654 資料:http://www.csharpkit.com/apigateway.html 官網:https://github.com/ThreeMammals/Ocelot 騰訊.Net大隊長“張善友”是專案主力開發人員之一。

基於以上的問題,API閘道器就可以解決以上的問題

API閘道器有很多種(比如zuul),我們想要說的是Ocelot

Ocelot就是一個提供了請求路由、安全驗證等功能的API閘道器微服務。

一、 Ocelot基本配置

1>建一個空的asp.net core專案。(我取名叫OcelotApp)

2>安裝 Install-Package Ocelot

3>專案根目錄下建立configuration.json配置檔案(名字自取)

configuration.json配置檔案設定如下(假設我的微服務中有一個用於傳送簡訊的MsgService微服務,一個用於提供產品的ProductService微服務,於是我在裡面就配置了關於這兩個微服務的轉發路由)

{/*這個用到的根節點就是一個ReRoutes陣列*/
  "ReRoutes": [
    {
      //第一個路由規則

      //這個路由就表示:當一個請求以MsgService為開頭,後面跟具體的URL,並且這個請求是get,或者post 那麼我就給他轉交給localhost:5001這個地址
      //例如:我的Ocelot的IP地址為113.118.195.106,監聽6008埠,當一個使用者請求這個地址
      //例如請求:http://113.118.195.106:6008/MsgService/Home/Index?name=lily
      //那麼我就將請求轉交給 http://localhost:5001/api/Home/Index?name=lily
      "DownstreamPathTemplate": "/api/{url}", //表示在url地址的前面加一個api
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/MsgService/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    },

    //第二個路由規則
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5003
        }
      ],
      "UpstreamPathTemplate": "/ProductService/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }

    //當然我們也可以新增跟多的路由
  ]
}

Program類

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace OcelotApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {

            var config = new ConfigurationBuilder().AddCommandLine(args).Build();
            string ip = config["ip"];
            string port = config["port"];

            return WebHost.CreateDefaultBuilder(args)
                       .UseStartup<Startup>()
                   .UseUrls($"http://{ip}:{port}")

                   //在這裡載入configuration.json配置檔案
                   .ConfigureAppConfiguration((hostingContext, builder) =>
                   {

                       builder.AddJsonFile("configuration.json", false, true); //將configuration.json配置資料夾到IConfigurationBuilder中
                });
        }
    }
}

Startup類

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace OcelotApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

       
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot(Configuration);//將IConfiguration類物件Configuration載入到服務中註冊
        }


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

            app.UseOcelot().Wait(); //使用Ocelot中介軟體
        }
    }
}

呼叫:

啟用OcelotApp這個專案

然後,啟動我們的的Consul服務

我們現在也啟動這個MsgServer的專案(設定這個專案的ip地址為 127.0.0.1,監聽埠為5001)

然後我們開啟Postman這個軟體,在裡面請求OcelotApp這個專案