网关介绍

网关其实就是将我们写好的API全部放在一个统一的地址暴露在公网,提供访问的一个入口。在 .NET Core下可以使用Ocelot来帮助我们很方便的接入API 网关。与之类似的库还有ProxyKit,微软也发布了一个反向代理的库YARP
关于网关的介绍不多说了,网上文章也挺多的,这些都是不错的选择,听说后期Ocelot将会使用YARP来重写。本篇主要实践一下在.NET Core环境下使用YARP。

YARP介绍

YARP 在 .NET Core 基础结构之上实现,可在 Windows、Linux 或 MacOS 上使用。可以使用 SDK 和您喜欢的编辑器、微软视觉工作室或可视化工作室代码进行开发。
YARP 1.1 支持 ASP.NET 核心 3.1、 5.0 & 6.0。可以从 https://dotnet.microsoft.com/download/dotnet/ 下载 .NET 开发工具包。
对 .NET 5 的视觉工作室支持包含在 Visual Studio 2019 v16.8 或更高版本中。
对 .NET 6 的可视化工作室支持包含在 Visual Studio 2022 中。
文档:https://microsoft.github.io/reverse-proxy/articles/getting-started.html
Git: https://github.com/microsoft/reverse-proxy

入门示例

首先使用命令行创建一个“MyProxy.YarpDemo”ASP.NET Core 应用程序

添加项目引用

  1. Install-Package Yarp.ReverseProxy

添加 YARP 中间件

  1. var builder = WebApplication.CreateBuilder(args);
  2. builder.Services.AddReverseProxy()
  3. .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
  4. var app = builder.Build();
  5. app.MapReverseProxy();
  6. app.Run();

配置

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

  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Information",
  5. "Microsoft": "Warning",
  6. "Microsoft.Hosting.Lifetime": "Information"
  7. }
  8. },
  9. "AllowedHosts": "*",
  10. //YARP配置源
  11. "ReverseProxy": {
  12. "Routes": {
  13. "route1": {
  14. "ClusterId": "cluster1",
  15. "Match": {
  16. "Path": "{**catch-all}"
  17. }
  18. }
  19. },
  20. "Clusters": {
  21. "cluster1": {
  22. //PowerOfTwoChoices - 选择两个随机的目标,然后从中选择一个更少请求的目标
  23. //FirstAlphabetical - 字母序, Random - 随机, RoundRobin - 轮询
  24. //LeastRequests - 所有目标中选择分配请求最少的目标
  25. "LoadBalancingPolicy": "PowerOfTwoChoices",
  26. "Destinations": {
  27. "destination1": {
  28. "Address": "http://localhost:5202"
  29. }
  30. }
  31. }
  32. }
  33. }
  34. }

:::warning LoadBalancingPolicy配置项说明

  • PowerOfTwoChoices - 选择两个随机的目标,然后从中选择一个更少请求的目标
  • FirstAlphabetical - 字母序
  • Random - 随机
  • RoundRobin - 轮询
  • LeastRequests - 所有目标中选择分配请求最少的目标 :::

    配置项说明

    1. {
    2. "ReverseProxy": {
    3. // Routes 节点配置需要反向代理的路由表
    4. "Routes": {
    5. // 第一个路由配置(最简配置)
    6. "minimumroute" : { // 路由名称,可自定义
    7. // 该路由所关联的集群配置,也就是目标服务器配置
    8. "ClusterId": "minimumcluster",
    9. "Match": { // 匹配规则
    10. "Path": "{**catch-all}"
    11. }
    12. },
    13. // 第二个路由配置(全量)
    14. "allrouteprops" : {
    15. "ClusterId": "allclusterprops"
    16. "Order" : 100, // 路由顺序,数字越小优先级越高
    17. // 认证策略,可选 "Default", "Anonymous"
    18. "Authorization Policy" : "Anonymous",
    19. // Cors 策略,可选 "Default", "Disable"
    20. "CorsPolicy" : "Default",
    21. "Match": { //匹配 /something/*
    22. "Path": "/something/{**remainder}", // The path to match using ASP.NET syntax.
    23. // 限定 Host,不设置就是不限制
    24. "Hosts" : [ "www.aaaaa.com", "www.bbbbb.com"],
    25. // Heep Methods 限定,不指定就是不限制
    26. "Methods" : [ "GET", "PUT" ],
    27. "Headers": [ // 请求头限定,不指定就是不限制
    28. {
    29. "Name": "MyCustomHeader", // 请求头名称
    30. "Values": [ "value1", "value2", "another value" ], // 规则值
    31. // 匹配模式,可选:"ExactHeader", "HeaderPrefix", "Exists" , "Contains", "NotContains"
    32. "Mode": "ExactHeader",
    33. "IsCaseSensitive": true // 是否区分大小写
    34. }
    35. ],
    36. "QueryParameters": [ // 查询字符串限定,不设置就是不限制
    37. {
    38. "Name": "MyQueryParameter", // 参数名
    39. "Values": [ "value1", "value2", "another value" ], // 规则值
    40. "Mode": "Exact", // 匹配模式,可选 "Exact", "Prefix", "Exists" , "Contains", "NotContains"
    41. "IsCaseSensitive": true
    42. }
    43. ]
    44. },
    45. "MetaData" : { // 元数据(KV对象),可以在自定义扩展中使用
    46. "MyName" : "MyValue"
    47. },
    48. "Transforms" : [ // List of transforms. See ./Transforms.html for more details
    49. {
    50. "RequestHeader": "MyHeader",
    51. "Set": "MyValue",
    52. }
    53. ]
    54. }
    55. },
    56. // 转发服务器配置
    57. "Clusters": {
    58. "minimumcluster": {
    59. "Destinations": {
    60. "example.com": { // 目的地 1,名字自定义
    61. "Address": "http://www.example.com/" // 要转发的目标地址
    62. }
    63. }
    64. },
    65. "allclusterprops": { // 一个比较全面的目的地配置
    66. "Destinations": {
    67. "first_destination": {
    68. "Address": "https://contoso.com" // 目标地址
    69. },
    70. "another_destination": {
    71. "Address": "https://10.20.30.40",
    72. "Health" : "https://10.20.30.40:12345/test" // Health Check 地址,会覆盖 HealthCheck.Active 下的 Path
    73. }
    74. },
    75. "LoadBalancingPolicy" : "PowerOfTwoChoices", // 负载均衡策略: PowerOfTwoChoices - 选择两个随机的目标,然后从中选择一个更少请求的目标, "FirstAlphabetical" - 字母序, "Random" - 随机, "RoundRobin" - 轮询, "LeastRequests" - 所有目标中选择分配请求最少的目标
    76. "SessionAffinity": {
    77. "Enabled": true, // Defaults to 'false'
    78. "Policy": "Cookie", // Default, alternatively "CustomHeader"
    79. "FailurePolicy": "Redistribute", // default, Alternatively "Return503"
    80. "Settings" : {
    81. "CustomHeaderName": "MySessionHeaderName" // Defaults to 'X-Yarp-Proxy-Affinity`
    82. }
    83. },
    84. "HealthCheck": { // 健康检查配置
    85. "Active": { // Makes API calls to validate the health.
    86. "Enabled": "true",
    87. "Interval": "00:00:10", // 检查间隔
    88. "Timeout": "00:00:10", // 超时时间
    89. "Policy": "ConsecutiveFailures",
    90. "Path": "/api/health" // 健康检查地址
    91. },
    92. "Passive": { // Disables destinations based on HTTP response codes
    93. "Enabled": true, // Defaults to false
    94. "Policy" : "TransportFailureRateHealthPolicy", // Required
    95. "ReactivationPeriod" : "00:00:10" // 10s
    96. }
    97. },
    98. "HttpClient" : { // Configuration of HttpClient instance used to contact destinations
    99. "SSLProtocols" : "Tls13",
    100. "DangerousAcceptAnyServerCertificate" : false,
    101. "MaxConnectionsPerServer" : 1024,
    102. "EnableMultipleHttp2Connections" : true,
    103. "RequestHeaderEncoding" : "Latin1" // How to interpret non ASCII characters in header values
    104. },
    105. "HttpRequest" : { // Options for sending request to destination
    106. "ActivityTimeout" : "00:02:00",
    107. "Version" : "2",
    108. "VersionPolicy" : "RequestVersionOrLower",
    109. "AllowResponseBuffering" : "false"
    110. },
    111. "MetaData" : { // Custom Key value pairs
    112. "TransportFailureRateHealthPolicy.RateLimit": "0.5", // Used by Passive health policy
    113. "MyKey" : "MyValue"
    114. }
    115. }
    116. }
    117. }
    118. }

    运行项目