Ocelot閘道器(三)

ProZkb發表於2024-07-30

下面是一個在 .NET Core 中使用 Ocelot 的簡單示例。這個示例展示瞭如何設定 Ocelot 作為 API Gateway,將請求轉發到不同的後端微服務。

步驟 1:建立專案

  1. 建立一個新的 .NET Core Web 應用程式(API 專案):

    dotnet new webapi -n OcelotGateway
    cd OcelotGateway

    建立兩個簡單的後端微服務作為示例:
    ServiceA

    dotnet new webapi -n ServiceA
    cd ServiceA
    

    ServiceA/Controllers 目錄中,建立 ValuesController.cs

    using Microsoft.AspNetCore.Mvc;
    
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(new[] { "Value from Service A - 1", "Value from Service A - 2" });
        }
    }

    ServiceB

    dotnet new webapi -n ServiceB
    cd ServiceB

    ServiceB/Controllers 目錄中,建立 ValuesController.cs

    using Microsoft.AspNetCore.Mvc;
    
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(new[] { "Value from Service B - 1", "Value from Service B - 2" });
        }
    }

    步驟 2:新增 Ocelot
    在 OcelotGateway 專案中,新增 Ocelot NuGet 包:

    dotnet add package Ocelot

    建立 ocelot.json 配置檔案,在 OcelotGateway 專案的根目錄中新增 ocelot.json 檔案,內容如下:

    {
      "Routes": [
        {
          "DownstreamPathTemplate": "/api/values",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5001
            }
          ],
          "UpstreamPathTemplate": "/servicea/values",
          "UpstreamHttpMethod": [ "GET" ]
        },
        {
          "DownstreamPathTemplate": "/api/values",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5002
            }
          ],
          "UpstreamPathTemplate": "/serviceb/values",
          "UpstreamHttpMethod": [ "GET" ]
        }
      ]
    }

    步驟 3:配置 Ocelot

    Startup.cs 檔案中,新增 Ocelot 的配置:

    using Ocelot.DependencyInjection;
    using Ocelot.Middleware;
    
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    builder.Services.AddOcelot();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseHttpsRedirection();
    
    
    var summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    
    app.MapGet("/weatherforecast", () =>
    {
        var forecast = Enumerable.Range(1, 5).Select(index =>
            new WeatherForecast
            (
                DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                Random.Shared.Next(-20, 55),
                summaries[Random.Shared.Next(summaries.Length)]
            ))
            .ToArray();
        return forecast;
    })
    .WithName("GetWeatherForecast")
    .WithOpenApi();
    
    // 啟動 Ocelot
    await app.UseOcelot();
    
    app.Run();
    
    record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
    {
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }

    步驟 4:執行服務

    1. 在終端中,開啟三個終端視窗,分別啟動 Ocelot Gateway 和兩個微服務:
      • 啟動 ServiceA

        cd ServiceA dotnet run
      • 啟動 ServiceB

        cd ServiceB dotnet run
      • 啟動 OcelotGateway

        cd OcelotGateway dotnet run

    步驟 5:測試 API Gateway

    1. 使用 Postman 或瀏覽器測試 API Gateway:
      • 訪問 Service A:

        GET http://localhost:5000/servicea/values

        應該返回:

        ["Value from Service A - 1", "Value from Service A - 2"]
      • 訪問 Service B:

        GET http://localhost:5000/serviceb/values

        應該返回:

        ["Value from Service B - 1", "Value from Service B - 2"]



    解釋json

    {
      "Routes": [
        {
          "DownstreamPathTemplate": "/api/values",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5001
            }
          ],
          "UpstreamPathTemplate": "/servicea/values",
          "UpstreamHttpMethod": [ "GET" ]
        },
        {
          "DownstreamPathTemplate": "/api/values",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5002
            }
          ],
          "UpstreamPathTemplate": "/serviceb/values",
          "UpstreamHttpMethod": [ "GET" ]
        }
      ]
    }

    解析這個示例

    1. 第一條路由

      • 當客戶端傳送請求到 /servicea/values(UpstreamPathTemplate)時,Ocelot 會將請求轉發到 http://localhost:5001/api/values(DownstreamPathTemplate)。
    2. 第二條路由

      • 當客戶端傳送請求到 /serviceb/values 時,Ocelot 會將請求轉發到 http://localhost:5002/api/values

相關文章