<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-proxy</artifactId>
<version>5.0.1</version>
</dependency>
Web 模块
Vert.x Web 代理
Vert.x Web 代理提供了一个处理器,它使用 Vert.x Http Proxy 来处理反向代理逻辑。
此模块具有技术预览状态,这意味着 API 可能会在版本之间发生变化。 |
使用 Vert.x Web 代理
要使用 Vert.x Web 代理,请将以下依赖项添加到您的构建描述符的 dependencies 部分
-
Maven(在您的
pom.xml
中)
-
Gradle(在您的
build.gradle
文件中)
dependencies {
compile 'io.vertx:vertx-web-proxy:5.0.1'
}
基本 Web 代理
要使用 Vert.x Web 代理实现本地反向代理,您需要以下内容:
-
代理服务器,负责处理前端请求并使用
ProxyHandler
将它们转发到源服务器。 -
源服务器,负责处理来自代理服务器的请求并相应地处理响应。
现在,您已经有了整体概念,接下来让我们深入实现,首先从源服务器开始,然后是使用 ProxyHandler
的代理服务器。
源服务器(后端)
您只需创建源服务器并使用 Vert.x Web Router
处理请求,该源服务器监听端口 7070
。
HttpServer backendServer = vertx.createHttpServer();
Router backendRouter = Router.router(vertx);
backendRouter.route(HttpMethod.GET, "/foo").handler(rc -> {
rc.response()
.putHeader("content-type", "text/html")
.end("<html><body><h1>I'm the target resource!</h1></body></html>");
});
backendServer.requestHandler(backendRouter).listen(7070);
代理服务器
创建监听端口 8080
的代理服务器。
HttpServer proxyServer = vertx.createHttpServer();
Router proxyRouter = Router.router(vertx);
proxyServer.requestHandler(proxyRouter);
proxyServer.listen(8080);
使用 ProxyHandler
最后一个有趣的部分是将代理服务器请求路由到源服务器,因此您需要创建一个带有指定目标和 ProxyHandler
的 HttpProxy
。
HttpClient proxyClient = vertx.createHttpClient();
HttpProxy httpProxy = HttpProxy.reverseProxy(proxyClient);
httpProxy.origin(7070, "localhost");
proxyRouter
.route(HttpMethod.GET, "/foo").handler(ProxyHandler.create(httpProxy));
或者,您也可以直接在 ProxyHandler
中指定目标。
HttpClient proxyClient = vertx.createHttpClient();
HttpProxy httpProxy = HttpProxy.reverseProxy(proxyClient);
proxyRouter
.route(HttpMethod.GET, "/foo")
.handler(ProxyHandler.create(httpProxy, 7070, "localhost"));
最后,代理服务器的请求将方便地作为反向代理路由到源服务器。
|
为多个目标使用 ProxyHandler
为了将代理服务器请求路由到多个源服务器,您只需为每个服务器创建一个 HttpProxy
并独立指定目标。
HttpClient proxyClient = vertx.createHttpClient();
HttpProxy httpProxy1 = HttpProxy.reverseProxy(proxyClient);
httpProxy1.origin(7070, "localhost");
HttpProxy httpProxy2 = HttpProxy.reverseProxy(proxyClient);
httpProxy2.origin(6060, "localhost");
proxyRouter
.route(HttpMethod.GET, "/foo").handler(ProxyHandler.create(httpProxy1));
proxyRouter
.route(HttpMethod.GET, "/bar").handler(ProxyHandler.create(httpProxy2));