Netty 异步模型

Stella981
• 阅读 501

简介

  1. Netty中的 I/O 操作是异步的, 包括 Bind、Write、Connect 等操作会简单的返回一个ChannelFuture。
  2. 调用者不能立刻获得结果, 而是通过Future-Listener 机制, 用户可以方便的主动获取或者通过通知机制获得IO操作结果。
  3. Netty的异步模型是建立在future和callback之上的。callback就是回调。
  4. Future的核心思想是: 假设一个方法func(), 其计算过程可能很耗时, 等待func()返回不合适。那么就可以在调用func()的时候, 立马返回一个Future, 后续可以通过Future去监控方法func()的处理过程(即: Future-Listener机制)

Future说明

  1. 表示异步的结果, 可以通过它提供的方法来检测执行是否完成, 比如检索计算等。
  2. ChannelFuture是一个继承了Future类的接口, public interface ChannelFuture extends Future {}。可以添加监听器, 当监听的事件发生时, 就会通知到监听器。

ChannelFuture类注释

/**
 * The result of an asynchronous {@link Channel} I/O operation.
 * 异步I/O操作的执行结果
 * <p>
 * All I/O operations in Netty are asynchronous. 
 * Netty中的所有 I/O操作都是异步的
 * It means any I/O calls will return immediately with no guarantee that the 
 * requested I/O operation has been completed at the end of the call. 
 * 这意味着 任意 I/O 调用都会直接返回, 但是不能保证请求的I/O 操作在被调用前能够完成。
 *
 * Instead, you will be returned with a {@link ChannelFuture} instance which gives 
 * you the information about the result or status of the I/O operation.
 * 但是, 会有一个能提供该I/O操作的结果或状态的ChannelFuture类实例被返回。 
 * <p>
 *
 * A {@link ChannelFuture} is either <em>uncompleted</em> or <em>completed</em>.
 * channelFuture的状态可以是未完成的也可以是完成的。
 *
 * When an I/O operation begins, a new future object is created. 
 * 当一个 I/O 操作开始, 一个新的对象被创建。
 *
 * The new future is uncompleted initially - it is neither succeeded, failed, nor 
 * cancelled because the I/O operation is not finished yet.  
 * 新的future一开始是未完成状态, 它不是成功的, 失败的, 或取消的, 因为 I/O 操作并没有完成。
 * 
 * If the I/O operation is finished either successfully, with failure, or by 
 * cancellation, the future is marked as completed with more specific information, 
 * such as the cause of the failure.
 * 如果 I/O 操作是成功完成的, 失败的 或是 被取消状态, future就被标记为带有特定信息的完成状
 * 态, 比如导致失败的原因。
 * 
 * Please note that even failure and cancellation belong to the completed state.
 * 请记住, 即使是 失败 和 取消 都是完成状态
 * <pre>
 *                                      +---------------------------+
 *                                      | Completed successfully    |
 *                                      +---------------------------+
 *                                 +---->      isDone() = true      |
 * +--------------------------+    |    |   isSuccess() = true      |
 * |        Uncompleted       |    |    +===========================+
 * +--------------------------+    |    | Completed with failure    |
 * |      isDone() = false    |    |    +---------------------------+
 * |   isSuccess() = false    |----+---->      isDone() = true      |
 * | isCancelled() = false    |    |    |       cause() = non-null  |
 * |       cause() = null     |    |    +===========================+
 * +--------------------------+    |    | Completed by cancellation |
 *                                 |    +---------------------------+
 *                                 +---->      isDone() = true      |
 *                                      | isCancelled() = true      |
 *                                      +---------------------------+
 * </pre>
 *
 * Various methods are provided to let you check if the I/O operation has been
 * completed, wait for the completion, and retrieve the result of the I/O
 * operation. 
 * 有许多方法提供给你来检查 此I/O 操作是否完成, 在等待完成, 并取回 I/O 操作的结果。
 * It also allows you to add {@link ChannelFutureListener}s so you
 * can get notified when the I/O operation is completed.
 * 它还允许你添加 ChannelFuture监听器, 所以你能够在I/O 操作完成时被通知。 
 *
 * <h3>Prefer {@link #addListener(GenericFutureListener)} to {@link #await()}</h3>
 *
 * It is recommended to prefer {@link #addListener(GenericFutureListener)} to
 * {@link #await()} wherever possible to get notified when an I/O operation is
 * done and to do any follow-up tasks.
 * 当一个 I/O 操作被完成 并且 有接下来的任务要做时, 推荐使用 addListener(添加监听器)而不是 
 * await() 方法, 因为使用监听器的方式可以被通知。
 * <p>
 * {@link #addListener(GenericFutureListener)} is non-blocking.
 * addListener 方法是非阻塞的
 *
 * It simply adds the specified {@link ChannelFutureListener} to the {@link 
 * ChannelFuture}, and I/O thread will notify the listeners when the I/O operation 
 * associated with the future is done. 
 * 它仅仅添加了特定的ChannelFutureListener到ChannelFuture中, 并且 I/O 线程会在 与future
 * 相关联的 I/O 操作完成时通知监听器。 
 *
 * {@link ChannelFutureListener} yields the best performance and resource 
 * utilization because it does not block at all, but it could be tricky to implement 
 * a sequential logic if you are not used to event-driven programming.
 * 由于本身不阻塞, ChannelFutureListener(监听器) 能提供最好的效用 和 最好的资源利用率, 但
 * 是如果内没有习惯于事件启动编程模型, 实现一系列逻辑时可能会比较tricky。
 * 
 * <p>
 * By contrast, {@link #await()} is a blocking operation.  
 * 相比较之下, await() 方法是一个阻塞操作。
 * Once called, the caller thread blocks until the operation is done.  
 * 一旦被调用, 在操作结束之前, 调用者线程会一直阻塞。
 * It is easier to implement a sequential logic with {@link #await()}, but the 
 * caller thread blocks unnecessarily until the I/O operation is done and there's 
 * relatively expensive cost of inter-thread notification. 
 * 以await() 方法实现一系列的逻辑会相对简单, 但是调用者线程在I/O操作间有不必要的阻塞 以及 
 * 线程内部通信代价很高。
 * Moreover, there's a chance of dead lock in a particular circumstance, which is 
 * described below.
 * 此外, 在特殊情况下, 还有可能会产生死锁, 描述如下。
 *
 * <h3>Do not call {@link #await()} inside {@link ChannelHandler}</h3>
 * 不要在 ChannelHandler 中调用 await() 方法
 * <p>
 * The event handler methods in {@link ChannelHandler} are usually called by
 * an I/O thread. 
 * ChannelHandler中的事件处理方法通常是由 I/O 线程调用的。
 *
 * If {@link #await()} is called by an event handler method, which is called by the 
 * I/O thread, the I/O operation it is waiting for might never complete because
 * {@link #await()} can block the I/O operation it is waiting for, which is a dead 
 * lock.
 * 如果 await() 方法是被一个事件处理方法以 I/O 线程的形式调用的, 该 I/O 操作会因为await()
 * 方法阻塞了此 正在被等待的 I/O 操作, 从而导致死锁。
 * <pre>
 * // BAD - NEVER DO THIS 千万别做以下操作
 * {@code @Override}
 * public void channelRead({@link ChannelHandlerContext} ctx, Object msg) {
 *     {@link ChannelFuture} future = ctx.channel().close();
 *     future.awaitUninterruptibly();
 *     // Perform post-closure operation
 *     // ...
 * }
 *
 * // GOOD 好的操作
 * {@code @Override}
 * public void channelRead({@link ChannelHandlerContext} ctx, Object msg) {
 *     {@link ChannelFuture} future = ctx.channel().close();
 *     future.addListener(new {@link ChannelFutureListener}() {
 *         public void operationComplete({@link ChannelFuture} future) {
 *             // Perform post-closure operation
 *             // ...
 *         }
 *     });
 * }
 * </pre>
 * <p>
 * In spite of the disadvantages mentioned above, there are certainly the cases
 * where it is more convenient to call {@link #await()}. 
 * 尽管await()方法的缺点已经在上列出, 还是肯定会有使用它跟方便的情况
 * In such a case, please make sure you do not call {@link #await()} in an I/O 
 * thread. 
 * 在此情况下, 请确保你没有在I/O线程中调用await()
 * Otherwise, {@link BlockingOperationException} will be raised to prevent a dead 
 * lock.
 * 此外 BlockingOperationException(阻塞操作异常) 会被抛出来预防死锁
 *
 * <h3>Do not confuse I/O timeout and await timeout</h3>
 * 不要将 I/O 超时 和 await 超时 弄混
 *
 * The timeout value you specify with {@link #await(long)},
 * {@link #await(long, TimeUnit)}, {@link #awaitUninterruptibly(long)}, or
 * {@link #awaitUninterruptibly(long, TimeUnit)} are not related with I/O
 * timeout at all.
 * 你使用 await(long), await(long, TimeUnit), awaitUninterruptibly(long) 或
 * awaitUninterruptibly(long, TimeUnit)方法时的延时与 I/O 延迟无关。
 * 
 * If an I/O operation times out, the future will be marked as
 * 'completed with failure,' as depicted in the diagram above. 
 * 如果 I/O 操作延时, 该future 会被标记为 完成且失败, 就像途中描述的那样。
 *
 * For example, connect timeout should be configured via a transport-specific 
 * option:
 * 比如, 连接事件应当通过特定的传输选项配置
 * <pre>
 * // BAD - NEVER DO THIS 不要做以下操作
 * {@link Bootstrap} b = ...;
 * {@link ChannelFuture} f = b.connect(...);
 * f.awaitUninterruptibly(10, TimeUnit.SECONDS);
 * if (f.isCancelled()) {
 *     // Connection attempt cancelled by user
 *     // 连接请求被用户取消    
 * } else if (!f.isSuccess()) {
 *     // You might get a NullPointerException here because the future
 *     // might not be completed yet.
 *     // 你可能会得到一个空指针, 因为该future没有被完成。   
 *     f.cause().printStackTrace();
 * } else {
 *     // Connection established successfully
 *     // 连接建立成功   
 * }
 *
 * // GOOD 好的操作
 * {@link Bootstrap} b = ...;
 * // Configure the connect timeout option.
 * <b>b.option({@link ChannelOption}.CONNECT_TIMEOUT_MILLIS, 10000);</b>
 * {@link ChannelFuture} f = b.connect(...);
 * f.awaitUninterruptibly();
 *
 * // Now we are sure the future is completed.
 * // 此时我们可以确认该future已完成
 * assert f.isDone();
 *
 * if (f.isCancelled()) {
 *     // Connection attempt cancelled by user
 *     // 连接请求被用户取消  
 * } else if (!f.isSuccess()) {
 *     f.cause().printStackTrace();
 * } else {
 *     // Connection established successfully
 *     // 成功建立连接  
 * }
 * </pre>
 */

工作原理示意图

Netty 异步模型

  • inBound: 入栈
  • outBound: 出栈
  • 说明:
    1. 在使用Netty进行编程时, 拦截操作和转换出入栈数据只需要提供callback 或 利用future即可。
    2. 这使得链式操作简单、高效, 并有利于编写可重用的、通用的代码。
    3. Netty 框架的目标就是让你的业务逻辑从网络基础应用编码中分离出来。

Netty 异步模型

Future-Listener机制

  1. 当Future对象刚刚创建时, 处于非完成状态, 调用者可以通过返回的ChannelFuture来获取操作执行的状态, 注册监听函数来执行完成后的操作。
  2. 常见操作
    • 通过 isDone 方法来判断当前操作是否完成;
    • 通过 isSuccess 方法来判断已完成的当前操作是否成功;
    • 通过 getCause 方法来获取已完成的当前操作失败的原因;
    • 通过 isCancelled 方法来判断已完成的当前操作是否被取消;
    • 通过 addListener 方法来注册监听器, 当操作已完成(isDone 方法返回完成), 将会通知指定的监听器; 如果 Future 对象已完成, 则通知指定的监听器
点赞
收藏
评论区
推荐文章
Easter79 Easter79
2年前
spring上下文的异步Event事件
在实际开发中,我们经常会需要做一件事:在完成某一个动作之后,需要另外以同步或者异步的方式去通知另外的对象去完成额外的操作,比如:当用户下单成功之后,需要发异步消息到给到邮件系统发邮件(短信)通知用户。(这里就涉及到异步消息的概念)消息队列是我们用来解决系统与系统之间异步与解耦的极佳实践工具,而在应用内部这个级别上,有时候也会需要这样的异步消息通知机制
Wesley13 Wesley13
2年前
IO模型详解及应用
如何阅读这篇文章顺序1.1:了解同步异步和阻塞非阻塞    1.11:同步异步    1.12:阻塞非阻塞1.2:了解一次read操作需要的步骤1.3:五种模型1.1:I/O模型中的同步异步,阻塞非阻塞:1.11:同步和异步:synchronous,asyncronous
Stella981 Stella981
2年前
AsyncTask的用法
AsyncTask,即异步任务,是Android给我们提供的一个处理异步任务的类.通过此类,可以实现UI线程和后台线程进行通讯,后台线程执行异步任务,并把结果返回给UI线程..为什么需要使用异步任务?我们知道,Android中只有UI线程,也就是主线程才能进行对UI的更新操作,而其他线程是不能直接操作UI的.这样的好处是保证了UI的稳定性和准确性,避
Stella981 Stella981
2年前
Linux网络IO模型
同步和异步,阻塞和非阻塞_同步和异步_关注的是结果消息的通信机制同步:同步的意思就是调用方需要主动等待结果的返回异步:异步的意思就是不需要主动等待结果的返回,而是通过其他手段比如,状态通知,回调函数等。_阻塞和非阻塞_主要关注的是等待结果返回调用方的状态阻塞:是指
Stella981 Stella981
2年前
Netty概念之 Future 和 Promise
(一)jdk中future和netty中future的比较jdk中future://取消异步操作booleancancel(booleanmayInterruptIfRunning);//异步操作是否取消booleanisCancell
Stella981 Stella981
2年前
Netty入门
一、是什么  Netty是一个高性能、异步事件驱动、基于JavaNIO的异步的可扩展的客户端/服务器网络编程框架。  Netty提供了对TCP、UDP和文件传输的支持,作为一个异步NIO框架,Netty的所有IO操作都是异步非阻塞的,通过FutureListener机制,用户可以方便的主动获取或者通过通知机制获得IO操作结果
Stella981 Stella981
2年前
Linux的五种IO模型?
IO的同步、异步、阻塞、非阻塞同步、异步同步(synchronous):A调用B,B立刻处理A的请求(即使C紧接着调用B),并把最终结果返回给A。异步(asynchronous):A调用B,B立刻反馈A,仅是状态,并非最终结果。B处
Wesley13 Wesley13
2年前
Java BIO
同步与异步,阻塞与非阻塞同步:当前线程发起了一个调用或请求,然后当前线程需要等待该调用结束返回结果才能继续往下进行其他操作。异步:当前线程发起了一个调用或请求,然后当前线程不需等待调用的执行结果就可以继续往下执行(请求交由另一个线程去执行),之后可以通过被调用者的状态改变或者被调用者主动发出通知来获得执行结果
Wesley13 Wesley13
2年前
5.4 异步TCP编程(二)
    5.4.2异步TCP应用编程的一般方法(本节可以忽略)  使用异步TCP编程时,除了套接字有对应的异步操作方式外,_TcpListener_和_TcpClient_类均提供了返回结果为_IAsyncResult_类型的异步操作的方法。    1、BeginAcceptTcpClient方法和EndAcceptTcpClien
Stella981 Stella981
2年前
Netty 线程模型与Reactor 模式
前言     Netty 的线程模型是基于NIO的Selector 构建的,使用了异步驱动的Reactor 模式来构建的线程模型,可以很好的支持成百上千的SocketChannel 连接。由于READ/WRITE 都是非阻塞的,可以充分提升I/O线程的运行效率,避免了IO阻塞导致线程挂起, 同时可以让一个线程支持对多个客户端的连接So