Netty和MongoDB异步回调无法协同工作

时间:2017-05-12 18:30:28

标签: java mongodb asynchronous netty

我有一个简单的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)
        });
    }
}

我可以看到它正在击中我的代码,但是响应永远不会被发送到客户端。如何在ServerHandler方法中进行异步调用?

1 个答案:

答案 0 :(得分:3)

您还需要拨打flush()或将write(...)更改为writeAndFlush(...),以确保内容真正刷新到套接字。