掌握 .NET Core 8 中的微服务:实现 Ocelot API 网关的分步指南
微服务架构已成为构建可扩展、灵活且可维护的系统的一种流行方法。它允许组织开发和部署独立的服务,每个服务都处理特定的业务功能。但是,管理多项服务会带来路由、安全性和流量管理等挑战。这就是 API 网关发挥关键作用的地方。
在本文中,我将向您介绍如何使用 .NET Core 8 中的 Ocelot API 网关实现微服务。在本教程结束时,您将了解如何配置 Ocelot 以进行路由、负载均衡和身份验证,并逐步实施基本的微服务架构。
要按照本教程进行操作,您需要满足以下条件:
微服务架构将应用程序分解为小型、独立的服务,这些服务可以单独部署和管理。每个微服务都旨在处理特定的业务功能。这种模块化方法提高了可扩展性、敏捷性和容错能力。
API Gateway 充当多个微服务的单个入口点。它处理路由、安全性、负载平衡、监控和其他横切关注点。API Gateway 抽象化了各个服务的复杂性,使客户端能够更轻松地使用 API。
Ocelot 是专为 .NET 应用程序构建的轻量级且功能强大的 API 网关框架。它通过提供路由、请求聚合、身份验证、速率限制和其他基本功能来简化微服务管理。使用 Ocelot,您可以在 .NET Core 应用程序中高效管理多个微服务。
让我们从创建两个微服务开始:和 .这些微服务将充当公开 API 的独立服务。ProductServiceOrderService
dotnet new sln -n MicroservicesWithOcelot
cd MicroservicesWithOcelot
dotnet new webapi -n ProductService
dotnet new webapi -n OrderService
2. 配置每个微服务:
每个服务都应该独立运行并公开自己的 API 集,这些 API 稍后将通过 API Gateway 进行路由。
接下来,使用 Ocelot 创建 API 网关,以将请求路由到微服务。
dotnet new webapi -n APIGateway
**2. 安装 Ocelot:**在项目中,从 NuGet 安装 Ocelot:APIGateway
dotnet add package Ocelot
Ocelot 将充当反向代理,将请求路由到相应的下游服务 ( 和 )。ProductServiceOrderService
现在,配置 Ocelot 以处理请求并将其路由到微服务。
示例 :ocelot.json
{
"Routes": [
{
"DownstreamPathTemplate": "/api/products",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"UpstreamPathTemplate": "/gateway/products",
"UpstreamHttpMethod": [ "GET" ]
},
{
"DownstreamPathTemplate": "/api/orders",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5002
}
],
"UpstreamPathTemplate": "/gateway/orders",
"UpstreamHttpMethod": [ "GET" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000"
}
}
要启用 Ocelot 路由,您需要在 API Gateway 中注册 Ocelot 中间件。
var builder = WebApplication.CreateBuilder(args);
// Add Ocelot configuration
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot();
var app = builder.Build();
// Use Ocelot middleware
app.UseOcelot().Wait();
app.Run();
**2. 构建并运行:**在不同的端口上运行所有项目(ProductService、OrderService 和 APIGateway)。例如:
现在,服务和网关已设置完毕,请使用 Postman 或 curl 测试 API 网关。
GET http://localhost:5000/gateway/products
GET http://localhost:5000/gateway/orders
向 API Gateway 添加身份验证可确保只有授权用户才能访问微服务。Ocelot 支持开箱即用的 JWT Bearer 身份验证。
{
"Routes": [
{
"DownstreamPathTemplate": "/api/products",
"AuthenticationOptions": {
"AuthenticationProviderKey": "AuthKey"
},
"UpstreamPathTemplate": "/gateway/products",
"UpstreamHttpMethod": [ "GET" ]
}
]
}
2. 在 中注册身份验证 :Program.cs
builder.Services.AddAuthentication("AuthKey")
.AddJwtBearer("AuthKey", options =>
{
options.Authority = "https://your-auth-provider";
options.Audience = "your-api";
});
Ocelot 可以处理同一微服务的多个实例之间的负载均衡。它还支持断路器,这有助于正常管理故障。
{
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5001 },
{ "Host": "localhost", "Port": 5003 }
],
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
**2.启用断路器:**要防止级联失败:
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 1000,
"TimeoutValue": 5000
}
2. 常见问题:JWT 鉴权失败。
在 .NET Core 微服务体系结构中使用 Ocelot API 网关有助于简化路由、安全性和流量管理的复杂性。