Skip to content

Commit c8470a7

Browse files
committed
add 编写大数据
1 parent c0d8b49 commit c8470a7

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

CORE FUNCTIONS/Writing big data.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
编写大数据
2+
====
3+
4+
由于网络的原因,如何有效的写大数据在异步框架是一个特殊的问题。因为写操作是非阻塞的,即便是在数据不能写出时,只是通知 ChannelFuture 完成了。当这种情况发生时,你必须停止写操作或面临内存耗尽的风险。所以写时,会产生大量的数据,我们需要做好准备来处理的这种情况下的缓慢的连接远端导致延迟释放内存的问题你。作为一个例子让我们考虑写一个文件的内容到网络。
5+
6+
在我们的讨论传输(见4.2节)时,我们提到了 NIO 的“zero-copy(零拷贝)”功能,消除移动一个文件的内容从文件系统到网络堆栈的复制步骤。所有这一切发生在 Netty 的核心,因此所有所需的应用程序代码是使用 interface FileRegion 的实现,在网状的API文档中定义如下为一个通过 Channel 支持 zero-copy 文件传输的文件区域。
7+
8+
下面演示了通过 zero-copy 将文件内容从 FileInputStream 创建 DefaultFileRegion 并写入 使用 Channel
9+
10+
Listing 8.11 Transferring file contents with FileRegion
11+
12+
FileInputStream in = new FileInputStream(file); //1
13+
FileRegion region = new DefaultFileRegion(in.getChannel(), 0, file.length()); //2
14+
15+
channel.writeAndFlush(region).addListener(new ChannelFutureListener() { //3
16+
@Override
17+
public void operationComplete(ChannelFuture future) throws Exception {
18+
if (!future.isSuccess()) {
19+
Throwable cause = future.cause(); //4
20+
// Do something
21+
}
22+
}
23+
});
24+
25+
1. 获取 FileInputStream
26+
2. 创建一个心的 DefaultFileRegion 用于文件的完整长度
27+
3. 发送 DefaultFileRegion 并且注册一个 ChannelFutureListener
28+
4. 处理发送失败
29+
30+
只是看到的例子只适用于直接传输一个文件的内容,没有执行的数据应用程序的处理。在相反的情况下,将数据从文件系统复制到用户内存是必需的,您可以使用 ChunkedWriteHandler。这个类提供了支持异步写大数据流不引起高内存消耗。
31+
32+
这个关键是 interface ChunkedInput,实现如下:
33+
34+
名称 | 描述
35+
-----|----
36+
ChunkedFile | 当你使用平台不支持 zero-copy 或者你需要转换数据,从文件中一块一块的获取数据
37+
ChunkedNioFile | 与 ChunkedFile 类似,处理使用了NIOFileChannel
38+
ChunkedStream | 从 InputStream 中一块一块的转移内容
39+
ChunkedNioStream | 从 ReadableByteChannel 中一块一块的转移内容
40+

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ This is the summary of my book.
5252
* [构建 Netty HTTP/HTTPS 应用](CORE FUNCTIONS/Building Netty HTTPHTTPS applications.md)
5353
* [空闲连接以及超时](CORE FUNCTIONS/Idle connections and Timeouts.md)
5454
* [解码分隔符和基于长度的协议](CORE FUNCTIONS/Decoding delimited and length-based protocols.md)
55+
* [编写大数据](CORE FUNCTIONS/Writing big data.md)
5556
* [Bootstrapping](CORE FUNCTIONS/Bootstrapping.md)
5657
* NETTY BY EXAMPLE
5758
* [单元测试](NETTY BY EXAMPLE/Unit Testing.md)

0 commit comments

Comments
 (0)