Netty 中非常多的异步调用,所以在介绍更多 NIO 相关的内容之前,我们来看看它的异步接口是怎么使用的。
前面我们在介绍 Echo 例子的时候,已经用过了 ChannelFuture 这个接口了:

争取在看完本节后,读者能搞清楚上面的这几行划线部分是怎么走的。
关于 Future 接口,我想大家应该都很熟悉,用得最多的就是在使用 Java 的线程池 ThreadPoolExecutor 的时候了。在 submit 一个任务到线程池中的时候,返回的就是一个 **Future** 实例,通过它来获取提交的任务的执行状态和最终的执行结果,我们最常用它的 isDone() 和 get() 方法。
下面是 JDK 中的 Future 接口 java.util.concurrent.Future :
public interface Future<V> {
// 取消该任务
boolean cancel(boolean mayInterruptIfRunning);
// 任务是否已取消
boolean isCancelled();
// 任务是否已完成
boolean isDone();
// 阻塞获取任务执行结果
V get() throws InterruptedException, ExecutionException;
// 带超时参数的获取任务执行结果
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
Netty 中的 Future 接口(同名)继承了 JDK 中的 Future 接口,然后添加了一些方法:
io.netty.util.concurrent.Future
public interface Future<V> extends java.util.concurrent.Future<V> {
// 是否成功
boolean isSuccess();
// 是否可取消
boolean isCancellable();
// 如果任务执行失败,这个方法返回异常信息
Throwable cause();
// 添加 Listener 来进行回调
Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);
Future<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
Future<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener);
Future<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
// 阻塞等待任务结束,如果任务失败,将“导致失败的异常”重新抛出来
Future<V> sync() throws InterruptedException;
// 不响应中断的 sync(),这个大家应该都很熟了
Future<V> syncUninterruptibly();
// 阻塞等待任务结束,和 sync() 功能是一样的,不过如果任务失败,它不会抛出执行过程中的异常
Future<V> await() throws InterruptedException;
Future<V> awaitUninterruptibly();
boolean await(long timeout,

本文详细解释了Netty中的异步接口,如Future、ChannelFuture和Promise,以及它们如何处理任务的异步执行、状态管理和回调机制。特别强调了sync()和await()方法的区别以及Listener在异步流程中的作用。
最低0.47元/天 解锁文章
954

被折叠的 条评论
为什么被折叠?



