淺析微軟的網關項目 -- ReverseProxy


淺析微軟的網關項目 ReverseProxy

Intro

最近微軟新開了一個項目 ReverseProxy ,也叫做 YARP(A Reverse Proxy)

官方介紹如下:

YARP is a reverse proxy toolkit for building fast proxy servers in .NET using the infrastructure from ASP.NET and .NET. The key differentiator for YARP is that it's been designed to be easily customized and tweaked to match the specific needs of each deployment scenario.

這是一個基於 .net (core) 和 asp.net (core) 的用來代理服務器的反向代理組件,YARP的主要區別在於它的設計易於定制和調整,以適應每種部署方案的特定需求。

你可以基於這個項目來構建自己的 API Gateway 項目

YARP 設計

YARP 主要是基於 endpoint 路由 + asp.net core 中間件來設計實現的

來看一下官方的示例 Startup 配置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddReverseProxy()
        .LoadFromConfig(_configuration.GetSection("ReverseProxy"))
        .AddProxyConfigFilter<CustomConfigFilter>();
}

/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
public void Configure(IApplicationBuilder app)
{
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapReverseProxy(proxyPipeline =>
        {
            // Custom endpoint selection
            proxyPipeline.Use((context, next) =>
            {
                var someCriteria = false; // MeetsCriteria(context);
                if (someCriteria)
                {
                    var availableDestinationsFeature = context.Features.Get<IAvailableDestinationsFeature>();
                    var destination = availableDestinationsFeature.Destinations[0]; // PickDestination(availableDestinationsFeature.Destinations);
                    // Load balancing will no-op if we've already reduced the list of available destinations to 1.
                    availableDestinationsFeature.Destinations = new[] { destination };
                }

                return next();
            });
            proxyPipeline.UseProxyLoadBalancing();
        });
    });
}

中間件

基於 asp.net core 的中間件的設計可以使得一些現有的 asp.net core 的中間件可以無縫集成,不得不說微軟的設計真的是很優秀

相對來說 Ocelot 的的設計就會稍顯遜色一些,因為 Ocelot 的設計是 asp.net core 的一個中間件,在 Ocelot 內部有自己的一套中間件,原來基於 asp.net core 的中間件要在 Ocelot 中使用就需要進一步開發,變成 Ocelot 的中間件,才能正常工作,比如 Ocelot 里的限流中間件就是基於一個 asp.net core 的中間件來實現的 AspNetCoreRateLimit

proxy endpoint 實現

public static void MapReverseProxy(this IEndpointRouteBuilder endpoints, Action<IApplicationBuilder> configureApp)
{
    if (endpoints is null)
    {
        throw new ArgumentNullException(nameof(endpoints));
    }
    if (configureApp is null)
    {
        throw new ArgumentNullException(nameof(configureApp));
    }

    var appBuilder = endpoints.CreateApplicationBuilder();
    appBuilder.UseMiddleware<DestinationInitializerMiddleware>();
    configureApp(appBuilder);
    appBuilder.UseMiddleware<ProxyInvokerMiddleware>();
    var app = appBuilder.Build();

    var routeBuilder = endpoints.ServiceProvider.GetRequiredService<IRuntimeRouteBuilder>();
    routeBuilder.SetProxyPipeline(app);

    var dataSource = (EndpointDataSource)endpoints.ServiceProvider.GetRequiredService<IProxyDynamicEndpointDataSource>();
    endpoints.DataSources.Add(dataSource);
}

從上面的代碼可以看到,針對反向代理的處理流程是也是一套中間件管道處理,

首先執行的是 DestinationInitializerMiddleware 在這一中間件,會獲取可用的下游節點,並通過 HttpContextFeatures 來傳遞給后面的中間件,

然后會調用傳進來的自定義中間件的邏輯,在這個邏輯中,可以加一些我們自己的業務邏輯,十分靈活,可擴展性極強

之后會執行 ProxyInvokerMiddleware,在這個中間件中會去調用下游服務,並生成 response 返回給客戶端

More

目前這個項目在還是在積極開發中,可以關注一下,但是暫時不建議在項目中使用,目前還沒發布 preview 版本,原本這個項目只支持 .net 5,不支持 .netcore3.1 ,在許多人的呼吁之下,微軟打算在 preview2 版本中提供對 dotnetcore 3.1 的支持,詳細可以參考 issue: https://github.com/microsoft/reverse-proxy/issues/159,希望提供 .net core 3.1 支持的可以去點個贊哈

Reference


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM