Java Netty和MongoDB异步回调不一起工作
我有一个简单的Netty测试服务器,我想查询mongo数据库并返回结果。我已经在Netty存储库中设置了简单的hello world教程: 我修改了简单教程,添加了一个异步MongoDB调用,该调用返回与示例相同的“hello world”字符串,但修改后HTTP调用永远不会完成 原始方法:Java Netty和MongoDB异步回调不一起工作,java,mongodb,asynchronous,netty,Java,Mongodb,Asynchronous,Netty,我有一个简单的Netty测试服务器,我想查询mongo数据库并返回结果。我已经在Netty存储库中设置了简单的hello world教程: 我修改了简单教程,添加了一个异步MongoDB调用,该调用返回与示例相同的“hello world”字符串,但修改后HTTP调用永远不会完成 原始方法: public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) {
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)
});
}
}
private final MongoCollection集合=。。。
公共无效channelRead(最终ChannelHandlerContext ctx,对象消息){
if(HttpRequest的消息实例){
最终HttpRequest请求=(HttpRequest)消息;
find(Filters.eq(“\u id”,new ObjectId(“…”)).first(new SingleResultCallback(){
公共作废onResult(文档文档,可丢弃){
布尔keepAlive=HttpUtil.isKeepAlive(req);
FullHttpResponse响应=。。。
(代码同上)
});
}
}
我可以看到它正在命中我的代码,但响应从未发送到客户端。如何在ServerHandler方法中进行异步调用?您还需要调用
flush()
或将write(…)
更改为writeAndFlush(…)
以确保内容真正刷新到套接字。您还需要调用flush()
或将write(…)
更改为writeAndFlush(…)
以确保内容真正刷新到套接字