Ocelot网关(三)

下面是一个在 .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
posted @ 2024-07-30 16:11  ProZkb  阅读(19)  评论(0编辑  收藏  举报