我想读取 InboundHandler
之外的类中特定位置的消息。我找不到从 netty 框架调用的 channelRead0
方法中读取它的方法。
例如:
context.writeMessage("message");
String msg = context.readMessage;
如果这是不可能的,我如何将在 channelRead0
方法中获得的结果映射到我在另一个类中进行的特定调用?
最佳答案
Netty框架被设计为异步驱动。使用这个类比,它可以用最少的线程使用来处理大量的连接。如果您正在创建一个使用 netty 框架将调用分派(dispatch)到远程位置的 api,您应该对您的调用使用相同的类比。
不要让你的 api 直接返回值,而是让它返回 Future<?>
或 Promise<?>
。在您的应用程序中实现此系统的方法有多种,最简单的方法是创建一个自定义处理程序,将传入请求映射到 Promise
位于 FIFO 队列中。
示例如下:
这很大程度上基于 this我过去提交的答案。
我们从处理程序开始,将请求映射到管道中的请求:
public class MyLastHandler extends SimpleInboundHandler<String> {
private final SynchronousQueue<Promise<String>> queue;
public MyLastHandler (SynchronousQueue<Promise<String>> queue) {
super();
this.queue = queue;
}
// The following is called messageReceived(ChannelHandlerContext, String) in 5.0.
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) {
this.queue.remove().setSuccss(msg);
// Or setFailure(Throwable)
}
}
然后我们需要一种将命令发送到远程服务器的方法:
Channel channel = ....;
SynchronousQueue<Promise<String>> queue = ....;
public Future<String> sendCommandAsync(String command) {
return sendCommandAsync(command, new DefaultPromise<>());
}
public Future<String> sendCommandAsync(String command, Promise<String> promise) {
synchronized(channel) {
queue.offer(promise);
channel.write(command);
}
channel.flush();
}
完成方法后,我们需要一种调用它的方法:
sendCommandAsync("USER anonymous",
new DefaultPromise<>().addListener(
(Future<String> f) -> {
String response = f.get();
if (response.startWidth("331")) {
// do something
}
// etc
}
)
);
如果被调用者想使用我们的 api 作为阻塞调用,他也可以这样做:
String response = sendCommandAsync("USER anonymous").get();
if (response.startWidth("331")) {
// do something
}
// etc
请注意 Future.get()
可以抛出 InterruptedException
如果Thread状态被中断,与socket读操作不同,只能通过socket上的一些交互来取消。此异常不应该成为 FutureListener
中的问题。 .
关于java - 如何在其他类中读取netty中的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34977477/