一、基本介绍
- 零拷贝是网络编程的关键,很多性能优化都离不开。
- 在 Java 程序中,常用的零拷贝有 mmap(内存映射)和 sendFile。那么,他们在 OS 里,到底是怎么样的一个的设计?我们分析 mmap 和 sendFile 这两个零拷贝。
- 另外我们看下 NIO 中如何使用零拷贝。
二、传统IO数据读写
Java 传统 IO 和网络编程的一段代码 ```java File file = new File(“test.txt”); RandomAccessFile raf = new RandomAccessFile(file, “rw”);
byte[] arr = new byte[(int) file.length()]; raf.read(arr);
Socket socket = new ServerSocket(8080).accept(); socket.getOutputStream().write(arr);
<a name="n8A74"></a># 三、传统的IO模型<br />**DMA**:direct memory access 直接内存拷贝(不使用 CPU)> 先从 hard drive(硬盘) 通过DMA拷贝到 kernel buffer(内核),经过CPU拷贝到 user buffer(用户数据在这里进行修改),经过 CPU拷贝到 socket buffer,最后经过 DMA拷贝到protocal engline(协议栈)。上诉过程,经过四次拷贝,三次状态切换 DMA copy --> cpu copy --> DMA copy<a name="ORhmB"></a># 四、mmap优化1. mmap 通过内存映射,将文件映射到内核缓冲区,同时,用户空间可以共享内核空间的数据(可以在这里该用户数据)。这样,在进行网络传输时,就可以减少内核空间到用户空间的拷贝次数。如下图1. mmap 示意图> 先从 hard drive(硬盘) 通过DMA拷贝到 kernel buffer(内核),经过 CPU拷贝到 socket buffer,最后经过 DMA拷贝到protocal engline(协议栈)。由于 mmap可以让 kernel buffer和user buffer 共享数据,所以少了一次拷贝,但是状态的切换还是三次<a name="IyCLU"></a># 五、sendFile 优化1. Linux2.1 版本提供了 sendFile 函数,其基本原理如下:数据根本不经过用户态,直接从内核缓冲区进入到 SocketBuffer,同时,由于和用户态完全无关,就减少了一次上下文切换1. 示意图和小结> 注意:所谓零拷贝是指没有CPU拷贝,但是这里依旧有CPU拷贝3. Linux在2.4 版本中,做了一些修改,避免了从内核缓冲区拷贝到 Socketbuffer 的操作,直接拷贝到协议栈,从而再一次减少了数据拷贝。具体如下图和小结:> 这里其实有一次 cpu 拷贝 kernel buffer -> socket buffer 但是,拷贝的信息很少,比如 lenght、offset 消耗低,可以忽略<a name="oDb7U"></a># 六、小总结<a name="Py7j4"></a>## 1、零拷贝的理解1. 我们说零拷贝,是从操作系统的角度来说的。因为内核缓冲区之间,没有数据是重复的(只有 kernel buffer 有一份数据)。1. 零拷贝不仅仅带来更少的数据复制,还能带来其他的性能优势,例如更少的上下文切换,更少的 CPU 缓存伪共享以及无 CPU 校验和计算。<a name="qQ9Tz"></a>## 2、mmap 和 sendFile 的区别1. mmap 适合小数据量读写,sendFile 适合大文件传输。1. mmap 需要 4 次上下文切换,3 次数据拷贝;sendFile 需要 3 次上下文切换,最少 2 次数据拷贝。1. sendFile 可以利用 DMA 方式,减少 CPU 拷贝,mmap 则不能(必须从内核拷贝到 Socket缓冲区)。<a name="HTmdN"></a># 七、零拷贝案例案例要求:1. 使用传统的 IO 方法传递一个大文件。1. 使用 NIO 零拷贝方式传递(transferTo)一个大文件。1. 看看两种传递方式耗时时间分别是多少。<a name="R5Dmi"></a>## 1、传统写法<a name="QaMbK"></a>### 服务端```javapublic class OldIoServer {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(7001);while (true) {try {Socket socket = serverSocket.accept();BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("test01.txt"));byte[] bytes = new byte[1024 * 1024 * 100];int len;while ((len = bufferedInputStream.read(bytes)) != -1) {System.out.println("输出");bufferedOutputStream.write(bytes, 0, len);}bufferedInputStream.close();bufferedOutputStream.close();socket.close();} catch (Exception ex) {ex.printStackTrace();}}}}
客户端
public class OldIoClient {public static void main(String[] args) throws IOException {Socket socket = new Socket("127.0.0.1", 7001);BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("/Users/superking/Desktop/test1.txt"));BufferedOutputStream bufferOutPutStream = new BufferedOutputStream(socket.getOutputStream());byte[] bytes = new byte[1024 * 1024 * 100];long readCount;long total = 0;long startTime = System.currentTimeMillis();while ((readCount = bufferedInputStream.read(bytes)) >= 0) {total += readCount;System.out.println("传输中。。。");bufferOutPutStream.write(bytes);}System.out.println("发送总字节数 " + total + ",耗时:" + (System.currentTimeMillis() - startTime));bufferOutPutStream.close();socket.close();bufferedInputStream.close();}}
2、使用 NIO 零拷贝
服务端
public class NewIoServer {public static void main(String[] args) throws IOException {ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();ServerSocket serverSocket = serverSocketChannel.socket();serverSocket.bind(new InetSocketAddress(7001));ByteBuffer byteBuffer = ByteBuffer.allocate(4096);BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("test01.txt"));while (true) {try {int readCount = 0;SocketChannel socketChannel = serverSocketChannel.accept();while ((readCount = socketChannel.read(byteBuffer)) != -1) {bufferedOutputStream.write(byteBuffer.array(), 0, readCount);byteBuffer.rewind(); // 倒带 position = 0, mark 作废}} catch (IOException e) {e.printStackTrace();}}}}
客户端
public class NewIoClient {public static void main(String[] args) throws IOException {SocketChannel socketChannel = SocketChannel.open();socketChannel.connect(new InetSocketAddress("127.0.0.1", 7001));FileChannel fileChannel = new FileInputStream("/Users/superking/Desktop/test1.txt").getChannel();long startTime = System.currentTimeMillis();// 在linux下的 transferTo 方法就可以完成传输// 在windows 下 一次调用 transferTo 只能发送 8m,需要分段传输文件// transferTo底层使用了零拷贝long count = fileChannel.transferTo(0, fileChannel.size(), socketChannel);System.out.println("发送总字节数=" + count + ",耗时:" + (System.currentTimeMillis() - startTime));fileChannel.close();}}
3、结论
零拷贝的速度明显快于传统IO。
