介紹
反向代理可以使用 Microsoft.Extensions 提供的 IConfiguration 抽象,從檔案中載入路由和叢集的組態。 此處提供的範例會使用 JSON,但任何 IConfiguration 來源都應該能夠運作。 如果來源檔案變更,組態也會更新,而不會重新啟動 Proxy。
載入設定
若要從 IConfiguration 載入 Proxy 組態,請在 Program.cs 中新增下列程式代碼:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add the reverse proxy capability to the server
builder.Services.AddReverseProxy()
// Initialize the reverse proxy from the "ReverseProxy" section of configuration
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
var app = builder.Build();
// Register the reverse proxy routes
app.MapReverseProxy();
app.Run();
您可以使用 組態篩選,在載入順序期間修改組態。
多個配置來源
自 1.1 起,YARP 支援從多個來源載入 Proxy 組態。 LoadFromConfig 可以多次呼叫參考不同的 IConfiguration 區段,也可以結合不同的組態來源,例如 InMemory。 路由可以參考來自其他來源的叢集。 請注意,不支持合併來自指定路由或叢集之不同來源的部分設定。
services.AddReverseProxy()
.LoadFromConfig(Configuration.GetSection("ReverseProxy1"))
.LoadFromConfig(Configuration.GetSection("ReverseProxy2"));
或
services.AddReverseProxy()
.LoadFromMemory(routes, clusters)
.LoadFromConfig(Configuration.GetSection("ReverseProxy"));
配置合約
檔案型組態會動態對應至 Yarp.ReverseProxy.Configuration 命名空間中的類型,IProxyConfigProvider 實作會在應用程式啟動時和每次變更時轉換。
組態結構
此組態包含您透過 Configuration.GetSection("ReverseProxy")指定的具名區段,並包含路由和叢集的子區段。
例:
{
"ReverseProxy": {
"Routes": {
"route1" : {
"ClusterId": "cluster1",
"Match": {
"Path": "{**catch-all}",
"Hosts" : [ "www.aaaaa.com", "www.bbbbb.com"]
}
}
},
"Clusters": {
"cluster1": {
"Destinations": {
"cluster1/destination1": {
"Address": "https://example.com/"
}
}
}
}
}
}
路線
路由區段是路由匹配項目及其相關聯配置的未排序集合。 路由至少需要下列欄位:
- RouteId - 唯一名稱
- ClusterId - 是指叢集區段中的項目名稱。
- Match - 包含 Hosts 陣列或路徑模式字串。 Path 是 ASP.NET Core 路由範本,可定義為 這裡所述。
路由比對是以優先順序最高的最特定路由為基礎,如這裡所述 。 您可以使用 [order] 字段達成明確排序,而較低的值會採用較高的優先順序。
標頭、授權、CORS,以及其他路由式原則,可以在每個路由條目上設定。 如需其他欄位,請參閱 RouteConfig。
Proxy 會套用指定的比對準則和原則,然後將要求傳遞至指定的叢集。
集群
叢集區段是具名叢集的未排序集合。 叢集主要包含具名目的地及其位址的集合,其中任何一個都被視為能夠處理指定路由的要求。 Proxy 會根據路由和叢集組態來處理要求,以選取目的地。
如需其他欄位,請參閱 ClusterConfig。
所有組態屬性
{
// Base URLs the server listens on, must be configured independently of the routes below
"Urls": "http://localhost:5000;https://localhost:5001",
"Logging": {
"LogLevel": {
"Default": "Information",
// Uncomment to hide diagnostic messages from runtime and proxy
// "Microsoft": "Warning",
// "Yarp" : "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ReverseProxy": {
// Routes tell the proxy which requests to forward
"Routes": {
"minimumroute" : {
// Matches anything and routes it to www.example.com
"ClusterId": "minimumcluster",
"Match": {
"Path": "{**catch-all}"
}
},
"allrouteprops" : {
// matches /something/* and routes to "allclusterprops"
"ClusterId": "allclusterprops", // Name of one of the clusters
"Order" : 100, // Lower numbers have higher precedence
"MaxRequestBodySize" : 1000000, // In bytes. An optional override of the server's limit (30MB default). Set to -1 to disable.
"AuthorizationPolicy" : "Anonymous", // Name of the policy or "Default", "Anonymous"
"CorsPolicy" : "Default", // Name of the CorsPolicy to apply to this route or "Default", "Disable"
"Match": {
"Path": "/something/{**remainder}", // The path to match using ASP.NET syntax.
"Hosts" : [ "www.aaaaa.com", "www.bbbbb.com"], // The host names to match, unspecified is any
"Methods" : [ "GET", "PUT" ], // The HTTP methods that match, uspecified is all
"Headers": [ // The headers to match, unspecified is any
{
"Name": "MyCustomHeader", // Name of the header
"Values": [ "value1", "value2", "another value" ], // Matches are against any of these values
"Mode": "ExactHeader", // or "HeaderPrefix", "Exists" , "Contains", "NotContains", "NotExists"
"IsCaseSensitive": true
}
],
"QueryParameters": [ // The query parameters to match, unspecified is any
{
"Name": "MyQueryParameter", // Name of the query parameter
"Values": [ "value1", "value2", "another value" ], // Matches are against any of these values
"Mode": "Exact", // or "Prefix", "Exists" , "Contains", "NotContains"
"IsCaseSensitive": true
}
]
},
"Metadata" : { // List of key value pairs that can be used by custom extensions
"MyName" : "MyValue"
},
"Transforms" : [ // List of transforms. See the Transforms article for more details
{
"RequestHeader": "MyHeader",
"Set": "MyValue"
}
]
}
},
// Clusters tell the proxy where and how to forward requests
"Clusters": {
"minimumcluster": {
"Destinations": {
"example.com": {
"Address": "http://www.example.com/"
}
}
},
"allclusterprops": {
"Destinations": {
"first_destination": {
"Address": "https://contoso.com"
},
"another_destination": {
"Address": "https://10.20.30.40",
"Health" : "https://10.20.30.40:12345/test" // override for active health checks
}
},
"LoadBalancingPolicy" : "PowerOfTwoChoices", // Alternatively "FirstAlphabetical", "Random", "RoundRobin", "LeastRequests"
"SessionAffinity": {
"Enabled": true, // Defaults to 'false'
"Policy": "Cookie", // Default, alternatively "CustomHeader"
"FailurePolicy": "Redistribute", // default, Alternatively "Return503Error"
"Settings" : {
"CustomHeaderName": "MySessionHeaderName" // Defaults to 'X-Yarp-Proxy-Affinity`
}
},
"HealthCheck": {
"Active": { // Makes API calls to validate the health.
"Enabled": "true",
"Interval": "00:00:10",
"Timeout": "00:00:10",
"Policy": "ConsecutiveFailures",
"Path": "/api/health", // API endpoint to query for health state
"Query": "?foo=bar"
},
"Passive": { // Disables destinations based on HTTP response codes
"Enabled": true, // Defaults to false
"Policy" : "TransportFailureRateHealthPolicy", // Required
"ReactivationPeriod" : "00:00:10" // 10s
}
},
"HttpClient" : { // Configuration of HttpClient instance used to contact destinations
"SSLProtocols" : "Tls13",
"DangerousAcceptAnyServerCertificate" : false,
"MaxConnectionsPerServer" : 1024,
"EnableMultipleHttp2Connections" : true,
"RequestHeaderEncoding" : "Latin1", // How to interpret non ASCII characters in request header values
"ResponseHeaderEncoding" : "Latin1" // How to interpret non ASCII characters in response header values
},
"HttpRequest" : { // Options for sending request to destination
"ActivityTimeout" : "00:02:00",
"Version" : "2",
"VersionPolicy" : "RequestVersionOrLower",
"AllowResponseBuffering" : "false"
},
"Metadata" : { // Custom Key value pairs
"TransportFailureRateHealthPolicy.RateLimit": "0.5", // Used by Passive health policy
"MyKey" : "MyValue"
}
}
}
}
}
如需詳細資訊,請參閱 記錄組態 和 HTTP 用戶端組態。