소개
역방향 프록시는 Microsoft.Extensions의 IConfiguration 추상화를 사용하여 파일에서 경로 및 클러스터에 대한 구성을 로드할 수 있습니다. 여기에 제공된 예제에서는 JSON을 사용하지만 모든 IConfiguration 원본이 작동합니다. 원본 파일이 변경되면 프록시를 다시 시작하지 않고도 구성이 업데이트됩니다.
구성 불러오기
IConfiguration에서 프록시 구성을 로드하려면 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는 여러 원본에서 프록시 구성 로드를 지원합니다. LoadFromConfig는 다른 IConfiguration 섹션을 참조하는 여러 번 호출되거나 InMemory와 같은 다른 구성 원본과 결합될 수 있습니다. 경로는 다른 원본에서 클러스터를 참조할 수 있습니다. 지정된 경로 또는 클러스터에 대해 다른 원본에서 부분 구성을 병합하는 것은 지원되지 않습니다.
services.AddReverseProxy()
.LoadFromConfig(Configuration.GetSection("ReverseProxy1"))
.LoadFromConfig(Configuration.GetSection("ReverseProxy2"));
또는
services.AddReverseProxy()
.LoadFromMemory(routes, clusters)
.LoadFromConfig(Configuration.GetSection("ReverseProxy"));
구성 계약
파일 기반 구성은 애플리케이션이 시작될 때 및 구성이 변경될 때마다 IProxyConfigProvider 구현에 의해 Yarp.ReverseProxy.Configuration 네임스페이스의 형식으로 동적으로 매핑됩니다.
구성 구조
구성은 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 - 호스트 배열 또는 경로 패턴 문자열을 포함합니다. 경로는 ASP.NET Core 경로 템플릿으로, 여기에 설명된 대로정의할 수 있습니다.
경로 일치는 가장 구체적인 경로가 가장 높은 우선 순위를 갖는 방식에 기반하며, 이는 에 설명되어 있습니다.
order
필드를 사용하여 명시적 순서를 지정할 수 있으며 값이 낮을수록 우선 순위가 높습니다.
헤더, 권한 부여, CORS및 기타 경로 기반 정책을 각 경로 항목에 구성할 수 있습니다. 추가 필드는 RouteConfig참조하세요.
프록시는 지정된 일치 조건 및 정책을 적용한 다음 지정된 클러스터에 요청을 전달합니다.
클러스터
클러스터 섹션은 명명된 클러스터의 순서가 지정되지 않은 컬렉션입니다. 클러스터에는 주로 명명된 대상 및 해당 주소의 컬렉션이 포함되며, 이 컬렉션은 지정된 경로에 대한 요청을 처리할 수 있는 것으로 간주됩니다. 프록시는 대상을 선택하기 위해 경로 및 클러스터 구성에 따라 요청을 처리합니다.
추가 필드는 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 클라이언트 구성참조하세요.
ASP.NET Core