【问题标题】:Netty and MongoDB async callback not working togetherNetty 和 MongoDB 异步回调不能一起工作
【发布时间】:2017-10-12 03:59:26
【问题描述】:

我有一个简单的 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 方法中进行异步调用?

【问题讨论】:

    标签: java mongodb asynchronous netty


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 2018-06-14
      • 2016-11-27
      • 1970-01-01
      相关资源
      最近更新 更多