如何获得所有已建立的连接到基于vertx的http服务器



我有一个由vertx http堆栈运行的https服务器。是否有方法获取所有已建立连接的客户端IP地址(即用于审核、安全、监控、QoS和其他目的(。理想情况下,我希望让事件(回调(驱动的API通知已建立和已关闭的连接。我怎样才能做到这一点?

目前的解决方法是轮询类似于netstat的工具,但这非常不方便,而且不是实时的(即可能会错过短连接(。

Github社区给出了答案:https://github.com/vert-x3/vertx-web/issues/685

您可以使用HttpServer连接处理程序并轻松管理它:

server.connectionHandler(conn -> {
// Track conn.remoteAddress()
conn.closeHandler(v -> {
// Cleanup track of conn.remoteAddress()
});
});

在我的示例中,我将把所有IP地址写入控制台。当然,您可以将其写入日志文件、数据库或您选择的其他位置。

Vertx vertx = Vertx.vertx();
// This your regular router
Router router = Router.router(vertx);
// We'll have two routes, just for fun
router.route("/a").handler((ctx) -> {
ctx.response().end("A");
});
router.route("/b").handler((ctx) -> {
ctx.response().end("B");
});

Router filterRouter = Router.router(vertx);
filterRouter.get().handler((ctx)->{
System.out.println("IP is " + ctx.request().remoteAddress());
// Forward to your actual router
ctx.next();
});
filterRouter.mountSubRouter("/", router);
vertx.createHttpServer().requestHandler(filterRouter::accept).listen(8080);

最新更新