gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:50:24 27 4
gpt4 key购买 nike

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

最佳答案

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

关于java - Netty 和 MongoDB 异步回调不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43944384/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com