Spring Cloud Gateway网关获取路由转发后的真实地址
在Spring Cloud Gateway中,你可以通过定义一个全局过滤器来获取路由后的实际地址。以下是一个简单的全局过滤器示例,它会记录请求被转发到的实际地址:
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
public class LogForwardedUrlFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
// 打印原始请求的URL
System.out.println("Original Request URL: " + request.getURI());
// 记录实际转发的地址
URI originalUri = request.getURI();
String scheme = originalUri.getScheme();
String host = originalUri.getHost();
int port = originalUri.getPort();
String path = originalUri.getPath();
String query = originalUri.getQuery();
// 获取转发后的地址
URI forwardedUrl = URI.create(scheme + "://" + host + (port != -1 ? ":" + port : "") + path + (query != null ? "?" + query : ""));
System.out.println("Forwarded URL: " + forwardedUrl);
// 继续过滤器链
return chain.filter(exchange);
}
}
然后,你需要将这个全局过滤器注册到Spring Cloud Gateway中:
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route", r -> r.path("/get")
.filters(f -> f.filter(new LogForwardedUrlFilter()))
.uri("http://httpbin.org:80"))
.build();
}
}
在这个配置中,当有请求匹配/get
路径时,会应用LogForwardedUrlFilter
过滤器,并打印出原始请求URL和实际转发的URL。这个例子使用了httpbin.org
作为下游服务的地址,你可以根据实际情况修改URI。
评论已关闭