基于 .NET 6 使用 YARP (Yet Another Reverse Proxy) 进行负载均衡

下面是基于 .NET 6 使用 YARP (Yet Another Reverse Proxy) 进行负载均衡,实现 ASP.NET Core API 的水平扩展的示例,包括详细的配置步骤和代码示例。


1. 创建 ASP.NET Core API 服务

首先,我们需要创建多个实例的 ASP.NET Core API 服务,它们将由 YARP 代理进行负载均衡。

1.1 创建 ASP.NET Core API

使用以下命令创建一个新的 Web API 项目:

dotnet new webapi -n BackendService
cd BackendService

1.2 修改 Program.cs

编辑 Program.cs,让 API 在不同的端口运行:

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/api/values", () =>
{
    var serverPort = app.Urls.FirstOrDefault();
    return Results.Ok(new { Message = "Hello from API", Server = serverPort });
});

app.Run();

1.3 运行多个实例

为了模拟多个服务实例,我们可以运行多个进程,每个实例监听不同的端口:

dotnet run --urls="http://localhost:5001"
dotnet run --urls="http://localhost:5002"
dotnet run --urls="http://localhost:5003"

此时,我们的 API 服务在 500150025003 端口运行。


2. 创建 YARP 反向代理

接下来,我们创建一个 YARP 代理应用程序,它会将请求负载均衡到上述 API 服务实例。

2.1 创建 YARP 代理项目

使用 .NET CLI 创建一个新的 ASP.NET Core 项目:

dotnet new web -n YarpGateway
cd YarpGateway

2.2 添加 YARP 依赖

dotnet add package Yarp.ReverseProxy

2.3 配置 appsettings.json

appsettings.json 中添加 YARP 配置:

{
  "ReverseProxy": {
    "Routes": {
      "default": {
        "ClusterId": "backend-cluster",
        "Match": {
          "Path": "{**catch-all}"
        }
      }
    },
    "Clusters": {
      "backend-cluster": {
        "Destinations": {
          "service1": { "Address": "http://localhost:5001" },
          "service2": { "Address": "http://localhost:5002" },
          "service3": { "Address": "http://localhost:5003" }
        },
        "LoadBalancingPolicy": "RoundRobin"
      }
    }
  }
}

LoadBalancingPolicy 支持:

  • FirstAlphabetical:选择字母顺序最前的后端
  • PowerOfTwoChoices:从两个随机选择的后端中选择最优的
  • Random:随机选择后端
  • RoundRobin:循环选择后端(默认)

2.4 配置 Program.cs

编辑 Program.cs,集成 YARP:

using Yarp.ReverseProxy;

var builder = WebApplication.CreateBuilder(args);

// 添加反向代理
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();

// 代理所有请求
app.MapReverseProxy();

app.Run();

3. 运行 YARP 代理

启动 YARP 代理:

dotnet run --urls="http://localhost:8000"

此时,我们可以通过 http://localhost:8000/api/values 访问后端 API,YARP 会自动将请求分发到 http://localhost:5001http://localhost:5002http://localhost:5003 之一。


4. 验证负载均衡

使用 curl 或浏览器多次访问:

curl http://localhost:8000/api/values

你会看到返回的 Server 地址在 500150025003 之间轮换,表明负载均衡生效。


5. 进一步优化

5.1 健康检查

可以在 appsettings.json 中启用健康检查:

"Clusters": {
  "backend-cluster": {
    "Destinations": {
      "service1": { "Address": "http://localhost:5001" },
      "service2": { "Address": "http://localhost:5002" },
      "service3": { "Address": "http://localhost:5003" }
    },
    "LoadBalancingPolicy": "RoundRobin",
    "HealthCheck": {
      "Active": {
        "Enabled": "true",
        "Interval": "00:00:10",
        "Timeout": "00:00:05",
        "Policy": "ConsecutiveFailures",
        "Path": "/health"
      }
    }
  }
}

并在 BackendServiceProgram.cs 添加健康检查端点:

app.MapGet("/health", () => Results.Ok("Healthy"));

5.2 配置动态后端

如果需要动态管理后端,可以使用 Consul 或 etcd 作为服务注册中心,让 YARP 自动发现新的服务实例。


6. 总结

  • 创建了多个 ASP.NET Core API 实例,分别监听 500150025003 端口。
  • 使用 YARP 作为反向代理,通过 http://localhost:8000 统一对外提供服务。
  • 配置 YARP 负载均衡,使用 RoundRobin 方式分发请求。
  • 添加健康检查,确保代理的后端实例正常运行。

这样,我们就完成了一个基于 .NET 6 + YARP 的负载均衡架构,实现了 ASP.NET Core API 的水平扩展。

你可能感兴趣的:(ASP.NET,Core,Web,API,.net,负载均衡)