使用 Ocelot API 網關實現微服務架構:從基礎到高級功能的詳細介紹
在現代微服務架構中,API 網關是連接客戶端與后端服務的重要組件,它負責請求的路由、負載均衡、身份驗證、聚合等功能。隨著微服務數量的增多,管理這些服務的復雜度也逐漸增加,而 Ocelot 作為一個輕量級的、基于 .NET 平臺的 API 網關,能夠簡化這一過程,提供強大的功能。
本文將通過一個電商應用的示例,詳細講解如何使用 Ocelot API 網關,從基礎配置到高級功能的實現,幫助開發者更好地理解和應用 Ocelot。
一、項目架構
在本示例中,我們假設開發了一個簡單的電商系統,包含以下幾個微服務:
- Product Service:提供產品信息(如獲取產品列表和單個產品的接口)。
- Order Service:處理訂單相關的操作(如創建訂單和獲取訂單詳情)。
- Customer Service:處理客戶信息(如獲取客戶資料)。
Ocelot 將作為統一的 API 網關,對外暴露統一入口,接收客戶端請求并路由到對應的微服務。同時,Ocelot 將處理一些高級功能,如請求聚合、身份驗證、限流等。
系統架構圖
+-------------------+
| |
| Ocelot API |
| Gateway |
| |
+--------+----------+
|
+---------+---------+---------+
| | |
+------v-------+ +-------v-------+ +-------v-------+
| Product | | Order | | Customer |
| Service | | Service | | Service |
| (5001) | | (5002) | | (5003) |
+-------------+ +---------------+ +---------------+
二、創建微服務
我們將依次創建 ProductService、OrderService 和 CustomerService,這三個服務將為 Ocelot 提供數據支持。
1. Product Service
首先創建一個簡單的 ProductService 微服務,它提供產品相關的信息。
創建 ProductService 項目
dotnet new webapi -n ProductService
在 Controllers 文件夾下創建 ProductController.cs,提供獲取產品列表和單個產品信息的接口:
using Microsoft.AspNetCore.Mvc;
namespace ProductService.Controllers
{
[ApiController]
[Route("api/v1/products")]
public class ProductController : ControllerBase
{
[HttpGet]
public IActionResult GetAllProducts()
{
var products = new[]
{
new { Id = 1, Name = "Product 1", Price = 100 },
new { Id = 2, Name = "Product 2", Price = 200 }
};
return Ok(products);
}
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
var product = new { Id = id, Name = "Product " + id, Price = id * 100 };
return Ok(product);
}
}
}
2. Order Service
接下來創建一個 OrderService 微服務,提供訂單相關的接口。
創建 OrderService 項目
dotnet new webapi -n OrderService
在 Controllers 文件夾下創建 OrderController.cs,提供獲取訂單信息的接口:
using Microsoft.AspNetCore.Mvc;
namespace OrderService.Controllers
{
[ApiController]
[Route("api/v1/orders")]
public class OrderController : ControllerBase
{
[HttpGet("{orderId}")]
public IActionResult GetOrderDetails(int orderId)
{
var order = new { OrderId = orderId, ProductId = 1, Quantity = 2, Total = 200 };
return Ok(order);
}
}
}
3. Customer Service
最后,創建一個 CustomerService 微服務,提供客戶信息的接口。
創建 CustomerService 項目
dotnet new webapi -n CustomerService
在 Controllers 文件夾下創建 CustomerController.cs,提供獲取客戶信息的接口:
using Microsoft.AspNetCore.Mvc;
namespace CustomerService.Controllers
{
[ApiController]
[Route("api/v1/customers")]
public class CustomerController : ControllerBase
{
[HttpGet("{customerId}")]
public IActionResult GetCustomerDetails(int customerId)
{
var customer = new { CustomerId = customerId, Name = "Customer " + customerId };
return Ok(customer);
}
}
}
三、創建 Ocelot API 網關
現在我們來創建 Ocelot API 網關,將來自客戶端的請求路由到不同的微服務。
1. 創建 Ocelot 項目
創建 OcelotApiGateway 項目
dotnet new webapi -n OcelotApiGateway
安裝 Ocelot 包
dotnet add package Ocelot
配置 Program.cs 文件
var builder = WebApplication.CreateBuilder(args);
// 注冊 Ocelot 服務
builder.Services.AddOcelot();
var app = builder.Build();
// 使用 Ocelot 中間件
app.UseOcelot().Wait();
app.Run();
2. 配置 ocelot.json 文件
在 Ocelot 項目根目錄下創建 ocelot.json 配置文件,定義請求路由規則:
{
"ReRoutes": [
{
"UpstreamPathTemplate": "/product",
"DownstreamPathTemplate": "/api/v1/products",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5001 }
],
"UpstreamHttpMethod": ["GET"]
},
{
"UpstreamPathTemplate": "/order/{orderId}",
"DownstreamPathTemplate": "/api/v1/orders/{orderId}",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5002 }
],
"UpstreamHttpMethod": ["GET"]
},
{
"UpstreamPathTemplate": "/customer/{customerId}",
"DownstreamPathTemplate": "/api/v1/customers/{customerId}",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5003 }
],
"UpstreamHttpMethod": ["GET"]
}
]
}
解釋:
/product請求會被 Ocelot 轉發到localhost:5001/api/v1/products。/order/{orderId}請求會被轉發到localhost:5002/api/v1/orders/{orderId}。/customer/{customerId}請求會被轉發到localhost:5003/api/v1/customers/{customerId}。
3. 配置啟動服務
在 Program.cs 文件中配置 Ocelot 服務,確保它在啟動時加載 ocelot.json 配置:
builder.Services.AddOcelot();
app.UseOcelot().Wait();
四、啟動微服務和 Ocelot API 網關
- 啟動 ProductService、OrderService 和 CustomerService,確保它們分別監聽端口
5001、5002和5003。 - 啟動 OcelotApiGateway,確保它監聽端口
5000。
五、訪問 API 網關
通過瀏覽器或 Postman 訪問 Ocelot API 網關:
- 訪問產品信息:
http://localhost:5000/product- Ocelot 會將請求轉發到
ProductService,返回產品列表。
- Ocelot 會將請求轉發到
- 訪問訂單詳情:
http://localhost:5000/order/1- Ocelot 會將請求轉發到
OrderService,返回訂單詳情。
- Ocelot 會將請求轉發到
- 訪問客戶信息:
http://localhost:5000/customer/1- Ocelot 會將請求轉發到
CustomerService,返回客戶信息。
- Ocelot 會將請求轉發到
六、高級功能:請求聚合和身份驗證
1. 請求聚合
假設你想要通過一個 API 聚合多個微服務的數據。例如,當客戶端請求 /order-details/{orderId} 時,你需要同時請求 OrderService 和 ProductService,然后將它們的響應合并后返回給客戶端。
更新 ocelot.json 文件以支持請求聚合:
{
"ReRoutes": [
{
"UpstreamPathTemplate": "/order-details/{orderId}",
"DownstreamPathTemplate": "/api/v1/orders/{orderId}",
"UpstreamHttpMethod": ["GET"],
"Aggregation": {
"RequestAggregations": [
{
"UpstreamPathTemplate": "/order-details/{orderId}",
"DownstreamPathTemplate": "/api/v1/orders/{orderId}",
"UpstreamHttpMethod": ["GET"]
},
{
"UpstreamPathTemplate": "/product-details/{orderId}",
"DownstreamPathTemplate": "/api/v1/products/{orderId}",
"UpstreamHttpMethod": ["GET"]
}
]
}
}
]
}
2. 身份驗證
假設你需要在 Ocelot 中為某些服務配置 JWT 身份驗證,確保只有授權用戶可以訪問相關服務。
更新 ocelot.json 文件配置身份驗證:
{
"ReRoutes": [
{
"UpstreamPathTemplate": "/product",
"DownstreamPathTemplate": "/api/v1/products",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5001 }
],
"UpstreamHttpMethod": ["GET"],
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer"
}
}
]
}
在 Program.cs 中配置 JWT 認證:
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
options.Authority = "https://your.auth.server";
options.Audience = "api1";
});
七、總結
通過這篇文章
,我們從創建微服務開始,到配置 Ocelot API 網關,再到實現高級功能(如請求聚合、身份驗證),逐步完成了一個完整的微服務架構。Ocelot 的靈活性和強大功能使得它在微服務架構中扮演著至關重要的角色,它不僅幫助開發者集中管理服務路由,還能有效地處理身份驗證、限流、負載均衡等關鍵任務。
希望本教程能夠幫助你更好地理解和使用 Ocelot,提升你的微服務架構的可管理性和可擴展性。如果你有任何問題或進一步的需求,歡迎隨時提出!

浙公網安備 33010602011771號