Yarp是微软开源的一个用.net实现的反向代理工具包,github库就叫reverse-proxy(反向代理)(吐槽一下微软起名字233333)
nuget包preview9之前都叫Microsoft.ReverseProxy,preview10变成Yarp.ReverseProxy了
放上链接https://github.com/microsoft/reverse-proxy

使用背景

由于公司技术历史原因,原来的网关规则是{paramA}_ {paramB} _ {paramC}_{paramD}这样子的。
想要换个新网关,又要兼容旧的这种规则,调研过目前几种API网关发现,apiSix支持这种操作(用$1占位符匹配参数)。
但是目前暂时不需要功能那么强大的api网关,而且不是.net技术实现的,出问题不好排查。
这是刚好发现Yarp这个东东,刚刚好符合需求,就拿来试试。

怎么用Yarp

Yarp主要要配置的东西就是Cluster(集群)和ProxyRoute(路由)
最简单的用法直接使用appsettings.json配置集群和路由配置
下面内容照搬Yarp 的Getting Started内容
详细的配置项可以直接看文档~~

"ReverseProxy": {
   "Routes": [
     {
       "RouteId": "route1",
       "ClusterId": "cluster1",
       "Match": {
         "Path": "{**catch-all}"
       },
     }
   ],
   "Clusters": {
     "cluster1": {
       "Destinations": {
         "cluster1/destination1": {
           "Address": "https://example.com/"
         }
       }
     }
   }
 }

需要在startup.cs中配置Yarp

public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services) 
{ 
    // Add the reverse proxy to capability to the server
    var proxyBuilder = services.AddReverseProxy();
    // Initialize the reverse proxy from the "ReverseProxy" section of configuration
    proxyBuilder.LoadFromConfig(Configuration.GetSection("ReverseProxy"));
} 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    // Enable endpoint routing, required for the reverse proxy
    app.UseRouting();
    // Register the reverse proxy routes
    app.UseEndpoints(endpoints => 
    {
        endpoints.MapReverseProxy(); 
    }); 
} 

改造一下用法,使用持久化储存配置

第一步,翻源码,找到配置的实体对象,照搬微调一遍,大概就是下图那么多个了。

第二步,实现IProxyConfigProvider和IProxyConfig,基本都是照搬原本代码微整形一下233333


由于源码里面ICertificateConfigLoader是internal类型,只能自己重新抄一次并实现了。

第三步,用EFCore持久化到数据库
搞个DBContext,把实体全部加进去,配置好关系之后,CodeFirst直接生成数据库哈哈哈哈

第四步,搞几个Management管理数据(CURD)

第五步,实现一下配置热更新
使用IChangeToken接口实现一个EFCoreReloadToken

第六步,再写个扩展方法替换原本的IProxyConfigProvider

最后一步,在Startup中用一下

services.AddReverseProxy()
                .LoadFromEFCore();

数据管理好了,差个界面(找前端小姐姐要一个)

第一步,搞个控制器,加上简单CURD接口

第二步,找前端小姐姐要个界面对接一下API


好了搞完可以用了,试一试

搞一个测试WebAPi

加一个集群

加一个路由

用Postman测一测

好了正常使用,搞定。

路由匹配可以用多个占位符自由组合,然后在PathPattern转换里面可以使用这些参数

测试一下性能1000个并发100000个请求

最后放下代码~~

欢迎吐槽提意见或者一起改进哈哈哈
ReverseProxy.Store

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/fanshaoO/p/14603159.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!