![]() |
VOOZH | about |
dotnet add package Galosys.Foundation.Yarp --version 26.5.20.1
NuGet\Install-Package Galosys.Foundation.Yarp -Version 26.5.20.1
<PackageReference Include="Galosys.Foundation.Yarp" Version="26.5.20.1" />
<PackageVersion Include="Galosys.Foundation.Yarp" Version="26.5.20.1" />Directory.Packages.props
<PackageReference Include="Galosys.Foundation.Yarp" />Project file
paket add Galosys.Foundation.Yarp --version 26.5.20.1
#r "nuget: Galosys.Foundation.Yarp, 26.5.20.1"
#:package Galosys.Foundation.Yarp@26.5.20.1
#addin nuget:?package=Galosys.Foundation.Yarp&version=26.5.20.1Install as a Cake Addin
#tool nuget:?package=Galosys.Foundation.Yarp&version=26.5.20.1Install as a Cake Tool
基于 YARP (Yet Another Reverse Proxy) 的网关核心模块,提供反向代理、JSON 配置管理和轻量级指标采集。
依赖: 仅依赖
Galosys.Foundation.Core,不依赖任何消息队列实现。
dotnet add package Galosys.Foundation.Yarp
在 appsettings.json 中配置路由:
{
"Gateway": {
"Routes": [
{
"Id": "user-service",
"Uri": "http://localhost:5001",
"Predicate": {
"Path": "/api/users/**"
}
}
]
}
}
在 Program.cs 中注册:
builder.Services.AddYarpCore(builder.Environment);
builder.Services.AddYarbConfigProvider<JsonYarpConfigProvider>(); // JSON 配置(默认)
app.MapYarpReverseProxy();
YARP 核心模块只负责广播配置刷新事件(通过 ICloudBus),不内置消费端。
使用 RabbitMQ 的项目需自行实现消费端 handler:
dotnet add package Galosys.Foundation.RabbitMQ.Client
using Galosys.Foundation.Core;
using Galosys.Foundation.Yarp;
using RabbitMQ.Client;
using Yarp.ReverseProxy.Configuration;
namespace YourApp.Handlers;
/// <summary>
/// RabbitMQ 分布式网关配置刷新消费者
/// </summary>
public class GatewayConfigRefreshedHandler : IMessageHandler<GatewayConfigRefreshedCloudEvent>
{
private readonly IYarpConfigManager _mgr;
private readonly ILogger<GatewayConfigRefreshedHandler> _logger;
public GatewayConfigRefreshedHandler(
IYarpConfigManager mgr,
ILogger<GatewayConfigRefreshedHandler> logger)
{
_mgr = mgr;
_logger = logger;
}
[AmqpHandler("base_gw_config_refreshed", true)]
public async Task<bool> HandleAsync(GatewayConfigRefreshedCloudEvent msg)
{
await Task.Run(() => _mgr.UpdateConfig());
_logger.LogInformation("=====网关路由已刷新=====");
return true;
}
}
默认关闭。需要在 appsettings.json 中显式开启:
{
"Gateway": {
"EnableRefreshEndpoint": true
}
}
开启后 /refresh 端点会触发配置刷新事件,且强制要求认证(RequireAuthorization())。
网关内置轻量级指标采集中间件 (GatewayMetricMiddleware),仅记录元数据(路径、方法、状态码、耗时),不缓冲请求/响应 Body。
配置节名称:Gateway:Metric
{
"Gateway": {
"Metric": {
"SamplingRate": 0.1, // 正常请求采样率,0.0-1.0(默认 0.1,即 10%)
"AlwaysLogErrors": true, // 异常/失败请求是否全量记录(默认 true)
"BatchSize": 200, // 批量写入 DB 的批次大小(默认 200)
"BatchIntervalMs": 500, // 批量写入最大间隔毫秒数(默认 500)
"BatchChannelCapacity": 50000 // 独立 Channel 容量(默认 50000)
}
}
}
SamplingRate 概率采样AlwaysLogErrors = true 时全量记录| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
SamplingRate |
double | 0.1 | 正常请求采样率,1.0 表示全量记录 |
AlwaysLogErrors |
bool | true | 异常请求全量记录,关闭后异常请求也按采样率采样 |
BatchSize |
int | 200 | 批量写入 DB 的批次大小 |
BatchIntervalMs |
int | 500 | 批量写入的最大间隔(ms) |
BatchChannelCapacity |
int | 50000 | Channel 容量,满时丢弃最旧日志 |
每条路由支持以下配置:
{
"Id": "order-service",
"Uri": "http://localhost:5002,http://localhost:5003", // 多地址负载均衡
"Predicate": {
"Path": "/api/orders/**,/api/payments/**", // 多路径逗号分隔
"Host": "api.example.com",
"Method": "GET,POST",
"Header": { "X-Version": "1" },
"QueryParameter": { "debug": "true" }
},
"LoadBalancer": "RoundRobin", // 可选:RoundRobin(默认)、LeastRequests、PowerOfTwoChoices 等
"Filter": {
"PathPrefix": "/api",
"PathRemovePrefix": "/api"
},
"Metadata": {
"custom-key": "custom-value"
}
}
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Id |
string | - | 路由唯一标识 |
Uri |
string | - | 目标服务地址,多地址逗号分隔 |
Predicate.Path |
string | - | 匹配路径,支持通配符,多路径逗号分隔 |
Predicate.Host |
string | - | 匹配主机名,多主机逗号分隔 |
Predicate.Method |
string | - | 匹配 HTTP 方法,多方法逗号分隔 |
Predicate.Header |
object | - | 匹配请求头键值对 |
Predicate.QueryParameter |
object | - | 匹配查询参数键值对 |
LoadBalancer |
string | "RoundRobin" |
负载均衡策略 |
Filter |
object | - | 路径转换(PathPrefix / PathRemovePrefix) |
Metadata |
object | - | 自定义元数据 |
网关内置限流、健康检查和超时机制,保护网关和后端服务稳定运行。配置节名称:Gateway:Ha
不配置 Gateway:Ha 节即可使用默认值:最大并发 2000、被动健康检查启用、默认超时 30s。
{
"Gateway": {
"Ha": {
"MaxConcurrentRequests": 2000, // 最大并发请求数(默认 2000)
"RateLimitStatusCode": 429, // 限流响应状态码(默认 429)
"PassiveHealthCheckEnabled": true, // 被动健康检查(默认 true)
"ActiveHealthCheckEnabled": false, // 主动健康检查(默认 false,启用后定期探测目标 /health)
"ActiveHealthCheckIntervalSeconds": 10, // 主动探测间隔秒数(默认 10)
"ActiveHealthCheckTimeoutSeconds": 5, // 主动探测超时秒数(默认 5)
"ReactivationPeriodSeconds": 60, // 不健康目标恢复等待秒数(默认 60)
"DefaultActivityTimeoutMs": 30000 // 默认请求超时毫秒数(默认 30000,即 30s)
}
}
}
GatewayRateLimitMiddleware 基于 SemaphoreSlim 限制最大并发请求数,超限立即返回 429(可配置状态码)。
MaxConcurrentRequests 时,请求正常通过MaxConcurrentRequests 时,立即返回 HTTP 429,不会转发到后端使用 YARP 内置 TransportFailureRate 策略,跟踪请求失败率,自动标记不健康目标并从负载均衡中排除。经过 ReactivationPeriodSeconds 后重新纳入候选。
启用后(ActiveHealthCheckEnabled = true),网关每隔 ActiveHealthCheckIntervalSeconds 向每个目标发送健康探测请求,超时 ActiveHealthCheckTimeoutSeconds。探测策略为 Any5xxResponse。
ForwarderRequestConfig.ActivityTimeout 控制转发请求超时。超时后网关立即返回 504 Gateway Timeout,不会继续等待。
DefaultActivityTimeoutMs(30000ms)RouterTemplate.ActivityTimeout 字段| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
MaxConcurrentRequests |
int | 2000 | 最大并发请求数 |
RateLimitStatusCode |
int | 429 | 限流响应状态码 |
PassiveHealthCheckEnabled |
bool | true | 是否启用被动健康检查 |
ActiveHealthCheckEnabled |
bool | false | 是否启用主动健康检查 |
ActiveHealthCheckIntervalSeconds |
int | 10 | 主动探测间隔(秒) |
ActiveHealthCheckTimeoutSeconds |
int | 5 | 主动探测超时(秒) |
ReactivationPeriodSeconds |
int | 60 | 不健康目标恢复等待(秒) |
DefaultActivityTimeoutMs |
int | 30000 | 默认请求超时(毫秒) |
配置节名称:Gateway:Config
{
"Gateway": {
"Config": {
"CacheExpirationSeconds": 30, // 数据库配置缓存过期秒数(默认 30s)
"EnablePollingFallback": false, // 是否启用轮询降级(默认 false,RabbitMQ 不可用时开启)
"PollingIntervalSeconds": 30 // 轮询间隔秒数(默认 30s)
}
}
}
DatabaseYarpConfigProvider 使用 IMemoryCache 缓存数据库查询结果,避免每次请求查库:
YarpDatabaseConfigCacheExpirationSeconds(默认 30s)UpdateConfig() 调用时自动清除缓存,下次请求重新查询 DB当 RabbitMQ 不可用时,可开启轮询降级模式,由 GatewayConfigPollingService(BackgroundService)定时刷新配置:
{
"Gateway": {
"Config": {
"EnablePollingFallback": true,
"PollingIntervalSeconds": 30
}
}
}
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
CacheExpirationSeconds |
int | 30 | 数据库配置缓存过期秒数 |
EnablePollingFallback |
bool | false | 是否启用轮询降级 |
PollingIntervalSeconds |
int | 30 | 轮询间隔秒数 |
Galosys.Foundation.Amqp 和 Galosys.Foundation.RabbitMQ.Client 的依赖。使用 RabbitMQ 分布式刷新的项目需自行实现 IMessageHandler<GatewayConfigRefreshedCloudEvent> 消费端(参考上方示例)。/refresh 端点默认关闭,需配置 Gateway:EnableRefreshEndpoint = true 并配合认证使用。GatewayHaOptions 高可用配置(配置节 Gateway:Ha)。新增 GatewayRateLimitMiddleware 限流中间件。启用 ActivityTimeout 超时和被动健康检查(默认行为变更:请求超过 30s 将返回 504)。IYarpConfigProvider 新增 GetConfigAsync() 方法(默认调用同步 GetConfig(),不影响现有实现)。JsonYarpConfigProvider 修复 hot reload(每次 GetConfig() 读取 IOptionsMonitor.CurrentValue)。YarpConfigManager.UpdateConfig() 添加异常处理和日志。新增 GatewayConfigOptions 配置缓存和轮询降级。| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 net8.0 is compatible. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
Showing the top 2 NuGet packages that depend on Galosys.Foundation.Yarp:
| Package | Downloads |
|---|---|
|
Galosys.Foundation.Yarp.NacosNaming
Galosys.Foundation快速开发库 |
|
|
Galosys.Foundation.Yarp.Database
Galosys.Foundation快速开发库 |
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 26.5.20.1 | 107 | 5/20/2026 |
| 26.5.19.1 | 131 | 5/19/2026 |
| 26.5.18.1 | 128 | 5/18/2026 |
| 26.5.15.1 | 131 | 5/15/2026 |
| 26.5.12.3 | 131 | 5/12/2026 |
| 26.5.12.2 | 89 | 5/12/2026 |
| 26.4.27.1-rc1 | 121 | 4/26/2026 |
| 26.4.25.1-rc1 | 118 | 4/25/2026 |
| 26.4.22.2-rc7 | 125 | 4/22/2026 |
| 26.4.22.2-rc6 | 118 | 4/22/2026 |
| 26.4.22.2-rc4 | 124 | 4/22/2026 |
| 26.4.22.2-rc3 | 124 | 4/22/2026 |
| 26.4.19.1-rc1 | 110 | 4/19/2026 |
| 26.4.12.8-rc1 | 126 | 4/12/2026 |
| 26.4.12.7-rc1 | 124 | 4/12/2026 |
| 26.1.30.1-rc1 | 170 | 1/30/2026 |
| 26.1.29.1 | 170 | 1/29/2026 |
| 26.1.28.5 | 171 | 1/28/2026 |
| 26.1.28.4 | 163 | 1/28/2026 |
| 26.1.28.2 | 165 | 1/28/2026 |