【发布时间】: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