当前位置:首页 > 技术文章 > 正文内容

使用YARP来实现负载均衡(负载均衡压测)

arlanguage3个月前 (01-31)技术文章41

YARP (“Yet Another Reverse Proxy”) 是一个库,可帮助创建高性能、生产就绪且高度可自定义的反向代理服务器。

YARP 是使用 ASP.NET 和 .NET(.NET 6 及更高版本)的基础结构在 .NET 上构建的,旨在通过 .NET 代码轻松自定义和调整,以满足每个部署方案的特定需求。所以,它支持配置文件,也可以基于自己的后端配置管理系统以编程方式管理配置。

许多现有代理都是为了支持 HTTP/1.1 而构建的,但随着工作负载更改为包括 gRPC 流量,它们需要 HTTP/2 支持,这需要更复杂的实现。通过使用 YARP,项目可以自定义路由和处理行为,而不必实现 http 协议。

同类应用#

YARP 的主要用途是负载均衡,它将请求路由到后端服务器,并根据负载均衡策略(如轮询、随机、权重等)将请求分发到后端服务器。目前流行的同类应用有 Nginx、HAProxy 等。

YARP 是在 .NET Core 基础结构之上实现的,可在 Windows、Linux 或 MacOS 上使用。 可以使用 SDK 和您最喜欢的编辑器 Microsoft Visual Studio 或 Visual Studio Code 进行开发。

创建新项目#

使用以下步骤生成的项目的完整版本可在基本 YARP 示例中找到。
首先,使用命令行创建一个 “Empty” ASP.NET Core 应用程序:

dotnet new web -n MyProxy -f net8.0

添加项目引用#

dotnet add package Yarp.ReverseProxy

添加 YARP 中间件#

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
var app = builder.Build();
app.MapReverseProxy();
app.Run();

配置#

YARP 的配置在 appsettings.json 文件中定义。有关详细信息,请参阅配置文件。
还可以通过编程方式提供配置。有关详细信息,请参阅 配置提供程序。
您可以通过查看 RouteConfig 和 ClusterConfig 来了解有关可用配置选项的更多信息。

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ReverseProxy": {
"Routes": {
"route1" : {
"ClusterId": "cluster1",
"Match": {
"Path": "{**catch-all}"
}
}
},
"Clusters": {
"cluster1": {
"Destinations": {
"destination1": {
"Address": "https://example.com/"
}
}
}
}
}
}

运行项目#

dotnet run --project <path to .csproj file>

其他配置#

我们创建了一个完整的YARP项目,可在Github上找到:Gateways

负载均衡#

创建了两个路由,baidu-route 和 example-route,分别对应百度和example.com。当使用localhost和127.0.0.1访问时,将请求转发到对应的后端服务器。有关详细信息,请参阅负载均衡。

{
"ReverseProxy": {
"Routes": {
"baidu-route" : {
"ClusterId": "baidu-cluster",
"Match": {
"Path": "{**catch-all}",
"Hosts": [ "localhost:5000" ]
}
},
"example-route" : {
"ClusterId": "example-cluster",
"Match": {
"Path": "{**catch-all}",
"Hosts": [ "127.0.0.1:5000" ]
},
}
},
"Clusters": {
"baidu-cluster": {
"Destinations": {
"destination1": {
"Address": "https://www.baidu.com/"
}
}
},
"example-cluster": {
"Destinations": {
"destination1": {
"Address": "https://example.com/"
}
}
}
}
}
}

缓存#

反向代理可用于缓存代理响应,并在请求代理到目标服务器之前提供请求。这可以减少目标服务器上的负载,增加一层保护,并确保在应用程序中实施一致的策略。此功能仅在使用 .NET 7.0 或更高版本时可用。有关详细信息,请参阅输出缓存。
输出缓存策略可以在 Program.cs 中配置,如下所示:

#region cache

string defaultCachePolicyName = "DefaultCache";
builder.Services.AddOutputCache(options =>
{
string expire = configuration["App:CacheExpire"] ?? "20";
int expireSeconds = int.Parse(expire);
options.AddPolicy("NoCache", build => build.NoCache());
options.AddPolicy(defaultCachePolicyName, build => build.Expire(TimeSpan.FromSeconds(20)));
options.AddPolicy("CustomCache", build => build.Expire(TimeSpan.FromSeconds(expireSeconds)));
});

#endregion

app.UseOutputCache();

增加OutputCachePolicy配置到路由中,如:

"baidu-route" : {
"ClusterId": "baidu-cluster",
"Match": {
"Path": "{**catch-all}",
"Hosts": [ "localhost:5000" ]
},
"OutputCachePolicy": "DefaultCache",
},

OutputCachePolicy值为:DefaultCache时,则使用默认缓存策略,缓存20秒。如:CustomCache,则使用自定义缓存策略, 自定义缓存时间, 读取配置文件App:CacheExpire。如果没有配置,或者配置NoCache,则不使用缓存功能。

限流#

反向代理可用于在将请求代理到目标服务器之前对请求进行速率限制。这可以减少目标服务器上的负载,增加一层保护,并确保在应用程序中实施一致的策略。此功能仅在使用 .NET 7.0 或更高版本时可用。有关详细信息,请参阅RateLimiter。
RateLimiter 策略可以在 Program.cs 中配置,如下所示:


#region rate limiter

string defaultRateLimiterPolicyName = "DefaultRateLimiter";
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter(defaultRateLimiterPolicyName, opt =>
{
opt.PermitLimit = 4;
opt.Window = TimeSpan.FromSeconds(12);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 2;
});
options.AddFixedWindowLimiter("CustomRateLimiter", opt =>
{
opt.PermitLimit = rateLimitOptions.PermitLimit;
opt.Window = TimeSpan.FromSeconds(rateLimitOptions.Window);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = rateLimitOptions.QueueLimit;
});
});

#endregion

app.UseRateLimiter();

增加RateLimiterPolicy配置到路由中,如:


"CustomRateLimit": {
"PermitLimit": 100,
"Window": 10,
"QueueLimit": 2
},


"baidu-route" : {
"ClusterId": "baidu-cluster",
"Match": {
"Path": "{**catch-all}",
"Hosts": [ "localhost:5000" ]
},
"RateLimiterPolicy": "DefaultRateLimiter"
},

RateLimiterPolicy值为:DefaultRateLimiter时,则使用默认限流策略,每12秒,最多允许4个请求。如:CustomRateLimiter,则使用自定义限流策略,自定义限流策略, 读取配置文件CustomRateLimit。如果没有配置,则不使用限流功能。

请求超时#

超时和超时策略可以通过 RouteConfig 为每个路由指定,并且可以从配置文件的各个部分进行绑定。与其他路由属性一样,可以在不重新启动代理的情况下修改和重新加载此属性。有关详细信息,请参阅请求超时。
超时策略可以在 Program.cs 中配置,如下所示:

#region timeouts
builder.Services.AddRequestTimeouts(options => { options.AddPolicy("CustomPolicy", TimeSpan.FromSeconds(30)); });
#endregion

app.UseRequestTimeouts();

30秒为自定义超时时间。
增加TimeoutPolicy配置到路由中,亦可以直接配置Timeout,如:

"baidu-route" : {
"ClusterId": "baidu-cluster",
"Match": {
"Path": "{**catch-all}",
"Hosts": [ "localhost:5000" ]
},
"Timeout": "00:00:30"
},
"example-route" : {
"ClusterId": "example-cluster",
"Match": {
"Path": "{**catch-all}",
"Hosts": [ "127.0.0.1:5000" ]
},
"TimeoutPolicy": "CustomPolicy"
}

TimeoutPolicy和Timeout不可同时配置到同一个路由上面。

跨域#

反向代理可以在跨域请求被代理到目标服务器之前处理这些请求。这可以减少目标服务器上的负载,并确保在应用程序中实施一致的策略。有关详细信息,请参阅跨域请求(CORS)。
跨域策略可以在 Program.cs 中配置,如下所示:

#region CORS

string defaultCorsPolicyName = "DefaultCors";
builder.Services.AddCors(options =>
{
options.AddPolicy(defaultCorsPolicyName, policy =>
{
string corsOrigins = configuration["App:CorsOrigins"] ?? "";
if (!string.IsOrWhiteSpace(corsOrigins))
{
string[] origins = corsOrigins.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.Select(x =>
{
return x.EndsWith("/", StringComparison.Ordinal) ? x.Substring(0, x.Length - 1) : x;
}).ToArray();

policy = policy.WithOrigins(origins);
}
else
{
policy = policy.AllowAnyOrigin();
}

policy.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});

#endregion

app.UseCors();

增加CorsPolicy配置到路由中,如:

"baidu-route" : {
"ClusterId": "baidu-cluster",
"Match": {
"Path": "{**catch-all}",
"Hosts": [ "localhost:5000" ]
},
"CorsPolicy": "DefaultCors"
},

CorsPolicy值为:DefaultCors时,则使用默认跨域策略。读取配置文件App:CorsOrigins。如果没有配置,则不使用跨域策略。

HTTPS#

HTTPS(HTTP over TLS 加密连接)是出于安全性、完整性和隐私原因在 Internet 上发出 HTTP 请求的标准方式。使用反向代理(如 YARP)时,需要考虑几个 HTTPS/TLS 注意事项。
YARP 是 7 级 HTTP 代理,这意味着传入的 HTTPS/TLS 连接由代理完全解密,因此它可以处理和转发 HTTP 请求。这通常称为 TLS 终止。到目标的传出连接可能加密,也可能不加密,具体取决于提供的配置。
有关详细信息,请参阅HTTPS。

builder.WebHost.ConfigureKestrel(kestrel =>
{
kestrel.ListenAnyIP(80);
kestrel.ListenAnyIP(443);
});

app.UseHsts();
app.UseHttpsRedirection();

自动生成HTTPS证书#

YARP 可以通过使用另一个 ASP.NET Core 项目 LettuceEncrypt 的 API 来支持证书颁发机构 Lets Encrypt。它允许您以最少的配置在客户端和 YARP 之间设置 TLS。有关详细信息,请参阅LettuceEncrypt。

builder.Services.AddLettuceEncrypt()
.PersistDataToDirectory(new DirectoryInfo(Path.Combine(env.ContentRootPath, "certs")), "");
builder.WebHost.ConfigureKestrel(kestrel =>
{
kestrel.ListenAnyIP(80);
kestrel.ListenAnyIP(443,
portOptions => { portOptions.UseHttps(h => { h.UseLettuceEncrypt(kestrel.ApplicationServices); }); });
});
"LettuceEncrypt": {
"AcceptTermsOfService": true,
"DomainNames": [
"example.com"
],
"EmailAddress": "it-admin@example.com"
}

DomainNames为域名,EmailAddress为邮箱地址。

使用中间件实现waf#

ASP.NET Core 使用中间件管道将请求处理划分为离散的步骤。应用程序开发人员可以根据需要添加和订购中间件。ASP.NET Core 中间件还用于实现和自定义反向代理功能。
反向代理IEndpointRouteBuilderExtensions 提供了一个重载,允许您构建一个中间件管道,该管道将仅针对与代理配置的路由匹配的请求运行。有关详细信息,请参阅Middleware。

app.MapReverseProxy(proxyPipeline =>
{
proxyPipeline.Use((context, next) =>
{
// Custom inline middleware

return next();
});
proxyPipeline.UseSessionAffinity();
proxyPipeline.UseLoadBalancing();
proxyPipeline.UsePassiveHealthChecks();
});

如果我们的应用对安全性验证要求比较高的话,我们可以使用中间件来实现waf。通过中间件对请求进行验证,比如新建一个WafMiddleware类:

namespace StargazerGateway;

public static class WafMiddleware
{
public static void UseWaf(this IReverseProxyApplicationBuilder proxyPipeline)
{
proxyPipeline.Use((context, next) =>
{
if (!CheckServerDefense(context))
{
context.Response.StatusCode = 444;
return context.Response.WriteAsync("I catch you!");
}
return next();
});
}

private static bool CheckServerDefense(HttpContext context)
{
if(!CheckHeader(context)) return false;
if(!CheckQueryString(context)) return false;
if(!CheckBody(context)) return false;
return true;
}

private static bool CheckHeader(HttpContext context)
{
// TODO: 检查请求头是否包含敏感词
return true;
}

private static bool CheckQueryString(HttpContext context)
{
if(context.Request.Query.ContainsKey("base64_encode")
|| context.Request.Query.ContainsKey("base64_decode")
|| context.Request.Query.ContainsKey("WEB-INF")
|| context.Request.Query.ContainsKey("META-INF")
|| context.Request.Query.ContainsKey("%3Cscript%3E")
|| context.Request.Query.ContainsKey("%3Ciframe")
|| context.Request.Query.ContainsKey("%3Cimg")
|| context.Request.Query.ContainsKey("proc/self/environ")
|| context.Request.Query.ContainsKey("mosConfig_"))
{
return false;
}
// TODO: 检查请求参数是否包含敏感词
return true;
}

private static bool CheckBody(HttpContext context)
{
if (context.Request.Method == "POST"
|| context.Request.Method == "PUT"
|| context.Request.Method == "PATCH")
{
// TODO: 读取请求体, 判断是否包含敏感词
// 重置请求体
context.Request.Body.Seek(0, SeekOrigin.Begin);
return true;
}

return true;
}
}

然后在反向代理中添加中间件:

app.MapReverseProxy(proxyPipeline =>
{
proxyPipeline.UseWaf();
proxyPipeline.UseSessionAffinity();
proxyPipeline.UseLoadBalancing();
proxyPipeline.UsePassiveHealthChecks();
});

中间件在调用时,会先检查请求头、请求参数、请求体,如果包含敏感词,则返回444状态码,表示请求被拦截。当然这些都会产生额外的开销,影响性能。因此需要根据实际情况进行优化。

  1. Microsoft Visual Studio: https://visualstudio.microsoft.com/vs/

  2. Visual Studio Code: https://code.visualstudio.com/

  3. YARP 示例 https://github.com/microsoft/reverse-proxy/tree/release/latest/samples/BasicYarpSample

  4. YARP 文档 https://microsoft.github.io/reverse-proxy/

  5. YARP 配置 https://microsoft.github.io/reverse-proxy/articles/config-files.html

  6. RouteConfig https://microsoft.github.io/reverse-proxy/api/Yarp.ReverseProxy.Configuration.RouteConfig.html

  7. ClusterConfig https://microsoft.github.io/reverse-proxy/api/Yarp.ReverseProxy.Configuration.ClusterConfig.html

  8. Gateways https://github.com/huangmingji/Stargazer.Abp.Template/tree/main/models/Gateways

  9. 负载均衡 https://microsoft.github.io/reverse-proxy/articles/load-balancing.html

  10. 输出缓存 https://microsoft.github.io/reverse-proxy/articles/output-caching.html

  11. RateLimiter https://microsoft.github.io/reverse-proxy/articles/rate-limiting.html

  12. 请求超时 https://microsoft.github.io/reverse-proxy/articles/timeouts.html

  13. 跨域请求(CORS)https://microsoft.github.io/reverse-proxy/articles/cors.html

  14. HTTPS https://microsoft.github.io/reverse-proxy/articles/https-tls.html

  15. LettuceEncrypt https://microsoft.github.io/reverse-proxy/articles/lets-encrypt.html

  16. Middleware https://microsoft.github.io/reverse-proxy/articles/middleware.html

扫描二维码推送至手机访问。

版权声明:本文由AR编程网发布,如需转载请注明出处。

本文链接:http://www.arlanguage.com/post/1541.html

标签: nginx asp.net
分享给朋友:

“使用YARP来实现负载均衡(负载均衡压测)” 的相关文章

【Nginx】Nginx 4种常见配置实例 nginx常用配置

本文主要介绍nginx 4种常见的配置实例。Nginx实现反向代理;Nginx实现负载均衡;Nginx实现动静分离;Nginx实现高可用集群;Nginx 4种常见配置实例如下:一、Nginx反向代理配置实例1.1 目标访问http://ip,访问到的是Tomcat的主页面http://ip:8080...

Nginx教程

NginxNginx1. 基本概念2. centos7部署nginx1. 部署前准备2. 安装nginx3. 配置文件1. nginx目录结构2. 默认的nginx.conf1. nginx.conf内容结构:2. nginx.conf内容格式说明:3. location 语法详解1. 语法规则:2...

docker安装php

本节将介绍在线使用Docker安装PHP解析器的步骤。通过本节的实操,您可以掌握从Docker环境的使用,PHP镜像以及Nginx服务器的拉取、导入、容器的启动的全部过程,从而具备使用Docker安装并部署PHP与ngninx的能力。本节要求您具备的基本能力有Linux,Docker,以及nginx...

php培训都学什么?有哪些课程?

PHP入门虽然比较容易简单,但是对于零基础学员来讲,想要学到精髓,并不是一件容易的事情,越到后面学起来越累,因此,最快最便捷的方法就是参加培训,不仅可以快速掌握入门,还能够学到精髓之处,那么PHP培训都有哪些课程?下面我们以六星教育的php培训课程为例来为大家讲解:第一阶段:动态网站开发的三个方面1...

Nginx如何配置正向代理:一步步教你轻松上手

Nginx作为一个高性能的HTTP和反向代理服务器,广泛应用于各类网站和服务中。然而,很多人可能不知道,Nginx同样可以配置为正向代理。今天我们就来详细讲解一下如何配置Nginx作为正向代理,让你的网络访问更加灵活便捷。什么是正向代理?正向代理是指客户端通过代理服务器访问目标服务器的过程。简单来说...

C# 实现高并发 Web 应用的性能优化秘籍

在现代的互联网应用中,尤其是大型 Web 应用,性能和可扩展性成为了核心竞争力。随着用户访问量和数据量的增大,高并发处理成为了系统稳定性和响应速度的关键因素。无论是电商平台、社交网站还是 SaaS 应用,如何应对海量用户的同时访问,确保系统高效运转,已经成为了技术人员面临的重要挑战。C# 和 ASP...