Netty 和 MongoDB 异步回调不能一起工作



我有一个简单的Netty测试服务器,我想查询一个mongo数据库并返回结果。我已经从Netty存储库设置了简单的hello world教程:https://github.com/netty/netty/tree/4.0/example/src/main/java/io/netty/example/http/helloworld

我已经修改了简单的教程以添加异步MongoDB调用,该调用返回与示例相同的"hello world"字符串,但是经过修改后,HTTP调用永远不会完成。

原始方法:

public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

我更改后:

private final MongoCollection<Document> collection = ...
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;
        collection.find(Filters.eq("_id", new ObjectId("..."))).first(new SingleResultCallback<Document>() {
            public void onResult(Document document, Throwable throwable) {
                boolean keepAlive = HttpUtil.isKeepAlive(req);
                FullHttpResponse response = ...
                (SAME CODE AS ABOVE)
        });
    }
}

我可以看到它击中了我的代码,但响应永远不会发送到客户端。如何在服务器处理程序方法中进行异步调用?

还需要调用flush()或将write(...)更改为writeAndFlush(...),以确保内容确实刷新到套接字。

最新更新