Tích hợp Ocelot trong .NET Core để xây dựng API Gateway

Ocelot là một thư viện mã nguồn mở giúp xây dựng API Gateway cho hệ thống microservice trên nền tảng .NET Core. Nó hỗ trợ nhiều tính năng mạnh mẽ như định tuyến, cân bằng tải, xác thực, giới hạn tốc độ, tích hợp với Consul, Polly và nhiều công cụ khác.

Cài đặt các gói cần thiết

Đảm bảo dự án sử dụng .NET 6.0 trở lên, sau đó cài đặt các package qua NuGet:

<PackageReference Include="Ocelot" Version="18.0.0" />
<PackageReference Include="Ocelot.Cache.CacheManager" Version="18.0.0" />
<PackageReference Include="Ocelot.Provider.Consul" Version="18.0.0" />
<PackageReference Include="Ocelot.Provider.Polly" Version="18.0.0" />

Đăng ký dịch vụ Ocelot trong Startup

Trong file Program.cs, cấu hình các dịch vụ mở rộng của Ocelot:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOcelot()
                .AddPolly()          // Hỗ trợ chính sách retry và circuit breaker
                .AddConsul()         // Tích hợp phát hiện dịch vụ qua Consul
                .AddCacheManager(cfg => cfg.WithDictionaryHandle()); // Cache đơn giản dạng từ điển

var app = builder.Build();
app.MapGet("/", () => "Gateway is running");

await app.UseOcelot(); // Kích hoạt Ocelot middleware
await app.Run();

Cấu hình định tuyến và gateway

Tạo file ocelot.json trong thư mục gốc dự án để định nghĩa các route:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/{everything}",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/gateway/{everything}",
      "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE" ],
      "ServiceName": "ProductService",
      "UseServiceDiscovery": true,
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      },
      "RateLimitOptions": {
        "EnableRateLimiting": true,
        "Period": "1m",
        "Limit": 10
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5000",
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500,
      "Type": "Consul"
    }
  }
}

Nạp cấu hình vào ứng dụng

Thêm đoạn code sau để tải file cấu hình khi khởi động ứng dụng:

builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);

Ví dụ cấu hình nâng cao với Consul và Polly

Dưới đây là ví dụ cấu hình tích hợp đầy đủ: discovery service, load balancing, rate limiting và circuit breaker:

{
  "Routes": [
    {
      "UpstreamPathTemplate": "/v1/products/{id}",
      "UpstreamHttpMethod": [ "GET" ],
      "DownstreamPathTemplate": "/api/products/{id}",
      "DownstreamScheme": "http",
      "ServiceName": "CatalogService",
      "UseServiceDiscovery": true,
      "LoadBalancerOptions": { "Type": "LeastConnection" },
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 2,
        "DurationOfBreak": 5000,
        "TimeoutValue": 3000
      },
      "RateLimitOptions": {
        "ClientWhitelist": [],
        "EnableRateLimiting": true,
        "Period": "10s",
        "Limit": 3
      }
    }
  ],
  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Host": "consul-server",
      "Port": 8500,
      "Type": "PollConsul",
      "PollingInterval": 2000
    },
    "RateLimitOptions": {
      "QuotaExceededMessage": "Vui lòng thử lại sau!",
      "HttpStatusCode": 429
    }
  }
}

Ocelot tự động chuyển hướng yêu cầu từ client đến service tương ứng, đồng thời áp dụng các chính sách bảo mật, giới hạn truy cập và xử lý lỗi theo cấu hình.

Thẻ: ocelot .NET-Core api-gateway consul polly

Đăng vào ngày 24 tháng 5 lúc 17:59