Netty 异步模型

简介

  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<Void> {}。可以添加监听器, 当监听的事件发生时, 就会通知到监听器。

ChannelFuture类注释

1/** 2 * The result of an asynchronous {@link Channel} I/O operation. 3 * 异步I/O操作的执行结果 4 * <p> 5 * All I/O operations in Netty are asynchronous. 6 * Netty中的所有 I/O操作都是异步的 7 * It means any I/O calls will return immediately with no guarantee that the 8 * requested I/O operation has been completed at the end of the call. 9 * 这意味着 任意 I/O 调用都会直接返回, 但是不能保证请求的I/O 操作在被调用前能够完成。 10 * 11 * Instead, you will be returned with a {@link ChannelFuture} instance which gives 12 * you the information about the result or status of the I/O operation. 13 * 但是, 会有一个能提供该I/O操作的结果或状态的ChannelFuture类实例被返回。 14 * <p> 15 * 16 * A {@link ChannelFuture} is either <em>uncompleted</em> or <em>completed</em>. 17 * channelFuture的状态可以是未完成的也可以是完成的。 18 * 19 * When an I/O operation begins, a new future object is created. 20 * 当一个 I/O 操作开始, 一个新的对象被创建。 21 * 22 * The new future is uncompleted initially - it is neither succeeded, failed, nor 23 * cancelled because the I/O operation is not finished yet. 24 * 新的future一开始是未完成状态, 它不是成功的, 失败的, 或取消的, 因为 I/O 操作并没有完成。 25 * 26 * If the I/O operation is finished either successfully, with failure, or by 27 * cancellation, the future is marked as completed with more specific information, 28 * such as the cause of the failure. 29 * 如果 I/O 操作是成功完成的, 失败的 或是 被取消状态, future就被标记为带有特定信息的完成状 30 * 态, 比如导致失败的原因。 31 * 32 * Please note that even failure and cancellation belong to the completed state. 33 * 请记住, 即使是 失败 和 取消 都是完成状态 34 * <pre> 35 * +---------------------------+ 36 * | Completed successfully | 37 * +---------------------------+ 38 * +----> isDone() = true | 39 * +--------------------------+ | | isSuccess() = true | 40 * | Uncompleted | | +===========================+ 41 * +--------------------------+ | | Completed with failure | 42 * | isDone() = false | | +---------------------------+ 43 * | isSuccess() = false |----+----> isDone() = true | 44 * | isCancelled() = false | | | cause() = non-null | 45 * | cause() = null | | +===========================+ 46 * +--------------------------+ | | Completed by cancellation | 47 * | +---------------------------+ 48 * +----> isDone() = true | 49 * | isCancelled() = true | 50 * +---------------------------+ 51 * </pre> 52 * 53 * Various methods are provided to let you check if the I/O operation has been 54 * completed, wait for the completion, and retrieve the result of the I/O 55 * operation. 56 * 有许多方法提供给你来检查 此I/O 操作是否完成, 在等待完成, 并取回 I/O 操作的结果。 57 * It also allows you to add {@link ChannelFutureListener}s so you 58 * can get notified when the I/O operation is completed. 59 * 它还允许你添加 ChannelFuture监听器, 所以你能够在I/O 操作完成时被通知。 60 * 61 * <h3>Prefer {@link #addListener(GenericFutureListener)} to {@link #await()}</h3> 62 * 63 * It is recommended to prefer {@link #addListener(GenericFutureListener)} to 64 * {@link #await()} wherever possible to get notified when an I/O operation is 65 * done and to do any follow-up tasks. 66 * 当一个 I/O 操作被完成 并且 有接下来的任务要做时, 推荐使用 addListener(添加监听器)而不是 67 * await() 方法, 因为使用监听器的方式可以被通知。 68 * <p> 69 * {@link #addListener(GenericFutureListener)} is non-blocking. 70 * addListener 方法是非阻塞的 71 * 72 * It simply adds the specified {@link ChannelFutureListener} to the {@link 73 * ChannelFuture}, and I/O thread will notify the listeners when the I/O operation 74 * associated with the future is done. 75 * 它仅仅添加了特定的ChannelFutureListener到ChannelFuture中, 并且 I/O 线程会在 与future 76 * 相关联的 I/O 操作完成时通知监听器。 77 * 78 * {@link ChannelFutureListener} yields the best performance and resource 79 * utilization because it does not block at all, but it could be tricky to implement 80 * a sequential logic if you are not used to event-driven programming. 81 * 由于本身不阻塞, ChannelFutureListener(监听器) 能提供最好的效用 和 最好的资源利用率, 但 82 * 是如果内没有习惯于事件启动编程模型, 实现一系列逻辑时可能会比较tricky。 83 * 84 * <p> 85 * By contrast, {@link #await()} is a blocking operation. 86 * 相比较之下, await() 方法是一个阻塞操作。 87 * Once called, the caller thread blocks until the operation is done. 88 * 一旦被调用, 在操作结束之前, 调用者线程会一直阻塞。 89 * It is easier to implement a sequential logic with {@link #await()}, but the 90 * caller thread blocks unnecessarily until the I/O operation is done and there's 91 * relatively expensive cost of inter-thread notification. 92 * 以await() 方法实现一系列的逻辑会相对简单, 但是调用者线程在I/O操作间有不必要的阻塞 以及 93 * 线程内部通信代价很高。 94 * Moreover, there's a chance of dead lock in a particular circumstance, which is 95 * described below. 96 * 此外, 在特殊情况下, 还有可能会产生死锁, 描述如下。 97 * 98 * <h3>Do not call {@link #await()} inside {@link ChannelHandler}</h3> 99 * 不要在 ChannelHandler 中调用 await() 方法 100 * <p> 101 * The event handler methods in {@link ChannelHandler} are usually called by 102 * an I/O thread. 103 * ChannelHandler中的事件处理方法通常是由 I/O 线程调用的。 104 * 105 * If {@link #await()} is called by an event handler method, which is called by the 106 * I/O thread, the I/O operation it is waiting for might never complete because 107 * {@link #await()} can block the I/O operation it is waiting for, which is a dead 108 * lock. 109 * 如果 await() 方法是被一个事件处理方法以 I/O 线程的形式调用的, 该 I/O 操作会因为await() 110 * 方法阻塞了此 正在被等待的 I/O 操作, 从而导致死锁。 111 * <pre> 112 * // BAD - NEVER DO THIS 千万别做以下操作 113 * {@code @Override} 114 * public void channelRead({@link ChannelHandlerContext} ctx, Object msg) { 115 * {@link ChannelFuture} future = ctx.channel().close(); 116 * future.awaitUninterruptibly(); 117 * // Perform post-closure operation 118 * // ... 119 * } 120 * 121 * // GOOD 好的操作 122 * {@code @Override} 123 * public void channelRead({@link ChannelHandlerContext} ctx, Object msg) { 124 * {@link ChannelFuture} future = ctx.channel().close(); 125 * future.addListener(new {@link ChannelFutureListener}() { 126 * public void operationComplete({@link ChannelFuture} future) { 127 * // Perform post-closure operation 128 * // ... 129 * } 130 * }); 131 * } 132 * </pre> 133 * <p> 134 * In spite of the disadvantages mentioned above, there are certainly the cases 135 * where it is more convenient to call {@link #await()}. 136 * 尽管await()方法的缺点已经在上列出, 还是肯定会有使用它跟方便的情况 137 * In such a case, please make sure you do not call {@link #await()} in an I/O 138 * thread. 139 * 在此情况下, 请确保你没有在I/O线程中调用await() 140 * Otherwise, {@link BlockingOperationException} will be raised to prevent a dead 141 * lock. 142 * 此外 BlockingOperationException(阻塞操作异常) 会被抛出来预防死锁 143 * 144 * <h3>Do not confuse I/O timeout and await timeout</h3> 145 * 不要将 I/O 超时 和 await 超时 弄混 146 * 147 * The timeout value you specify with {@link #await(long)}, 148 * {@link #await(long, TimeUnit)}, {@link #awaitUninterruptibly(long)}, or 149 * {@link #awaitUninterruptibly(long, TimeUnit)} are not related with I/O 150 * timeout at all. 151 * 你使用 await(long), await(long, TimeUnit), awaitUninterruptibly(long) 或 152 * awaitUninterruptibly(long, TimeUnit)方法时的延时与 I/O 延迟无关。 153 * 154 * If an I/O operation times out, the future will be marked as 155 * 'completed with failure,' as depicted in the diagram above. 156 * 如果 I/O 操作延时, 该future 会被标记为 完成且失败, 就像途中描述的那样。 157 * 158 * For example, connect timeout should be configured via a transport-specific 159 * option: 160 * 比如, 连接事件应当通过特定的传输选项配置 161 * <pre> 162 * // BAD - NEVER DO THIS 不要做以下操作 163 * {@link Bootstrap} b = ...; 164 * {@link ChannelFuture} f = b.connect(...); 165 * f.awaitUninterruptibly(10, TimeUnit.SECONDS); 166 * if (f.isCancelled()) { 167 * // Connection attempt cancelled by user 168 * // 连接请求被用户取消 169 * } else if (!f.isSuccess()) { 170 * // You might get a NullPointerException here because the future 171 * // might not be completed yet. 172 * // 你可能会得到一个空指针, 因为该future没有被完成。 173 * f.cause().printStackTrace(); 174 * } else { 175 * // Connection established successfully 176 * // 连接建立成功 177 * } 178 * 179 * // GOOD 好的操作 180 * {@link Bootstrap} b = ...; 181 * // Configure the connect timeout option. 182 * <b>b.option({@link ChannelOption}.CONNECT_TIMEOUT_MILLIS, 10000);</b> 183 * {@link ChannelFuture} f = b.connect(...); 184 * f.awaitUninterruptibly(); 185 * 186 * // Now we are sure the future is completed. 187 * // 此时我们可以确认该future已完成 188 * assert f.isDone(); 189 * 190 * if (f.isCancelled()) { 191 * // Connection attempt cancelled by user 192 * // 连接请求被用户取消 193 * } else if (!f.isSuccess()) { 194 * f.cause().printStackTrace(); 195 * } else { 196 * // Connection established successfully 197 * // 成功建立连接 198 * } 199 * </pre> 200 */

工作原理示意图

1576203568157

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

1576203623509

Future-Listener机制

  1. 当Future对象刚刚创建时, 处于非完成状态, 调用者可以通过返回的ChannelFuture来获取操作执行的状态, 注册监听函数来执行完成后的操作。
  2. 常见操作
    • 通过 isDone 方法来判断当前操作是否完成;
    • 通过 isSuccess 方法来判断已完成的当前操作是否成功;
    • 通过 getCause 方法来获取已完成的当前操作失败的原因;
    • 通过 isCancelled 方法来判断已完成的当前操作是否被取消;
    • 通过 addListener 方法来注册监听器, 当操作已完成(isDone 方法返回完成), 将会通知指定的监听器; 如果 Future 对象已完成, 则通知指定的监听器
点赞
收藏

评论区

加载中...

相关推荐

spring上下文的异步Event事件

在实际开发中,我们经常会需要做一件事:在完成某一个动作之后,需要另外以同步或者异步的方式去通知另外的对象去完成额外的操作,比如:当用户下单成功之后,需要发异步消息到给到邮件系统发邮件(短信)通知用户。(这里就涉及到异步消息的概念)消息队列是我们用来解决系统与系统之间异步与解耦的极佳实践工具,而在应用内部这个级别上,有时候也会需要这样的异步消息通知机制

IO模型详解及应用

如何阅读这篇文章顺序1.1:了解同步异步和阻塞非阻塞    1.11:同步异步    1.12:阻塞非阻塞1.2:了解一次read操作需要的步骤1.3:五种模型1.1:I/O模型中的同步异步,阻塞非阻塞:1.11:同步和异步:synchronous,asyncronous

AsyncTask的用法

AsyncTask,即异步任务,是Android给我们提供的一个处理异步任务的类.通过此类,可以实现UI线程和后台线程进行通讯,后台线程执行异步任务,并把结果返回给UI线程..为什么需要使用异步任务?我们知道,Android中只有UI线程,也就是主线程才能进行对UI的更新操作,而其他线程是不能直接操作UI的.这样的好处是保证了UI的稳定性和准确性,避

Linux网络IO模型

同步和异步,阻塞和非阻塞_同步和异步_关注的是结果消息的通信机制同步:同步的意思就是调用方需要主动等待结果的返回异步:异步的意思就是不需要主动等待结果的返回,而是通过其他手段比如,状态通知,回调函数等。_阻塞和非阻塞_主要关注的是等待结果返回调用方的状态阻塞:是指

Netty概念之 Future 和 Promise

(一)jdk中future和netty中future的比较jdk中future://取消异步操作booleancancel(booleanmayInterruptIfRunning);//异步操作是否取消booleanisCancell

Netty入门

一、是什么  Netty是一个高性能、异步事件驱动、基于JavaNIO的异步的可扩展的客户端/服务器网络编程框架。  Netty提供了对TCP、UDP和文件传输的支持,作为一个异步NIO框架,Netty的所有IO操作都是异步非阻塞的,通过FutureListener机制,用户可以方便的主动获取或者通过通知机制获得IO操作结果