NIO 与零拷贝
- 一. NIO 与零拷贝
- 二. 传统 IO 数据拷贝
- 三. 传统 IO 模型
- 四. mmap 优化
- 五. sendFile 优化
- 六. 零拷贝总结
- 七. mmap 和 sendFile 的区别
- 八. NIO零拷贝案例(比较原生IO拷贝文件速度)
一. NIO 与零拷贝
零拷贝基本介绍
- 零拷贝是网络编程的关键,很多性能优化都离不开。
- 在 Java 程序中,常用的零拷贝有 mmap(内存映射) 和 sendFile。
传统 IO 数据读写Java 传统 IO 和 网络编程的一段代码
二. 传统 IO 数据拷贝
OldIOClient _客户端
package com.xizi.zerocopy;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Socket;
public class OldIOClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 7001);
String fileName = "数据结构和算法.zip";
InputStream inputStream = new FileInputStream(fileName);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
byte[] buffer = new byte[4096];
long readCount;
long total = 0;
long startTime = System.currentTimeMillis();
while ((readCount = inputStream.read(buffer)) >= 0) {
total += readCount;
dataOutputStream.write(buffer);
}
System.out.println("发送总字节数: " + total + ", 耗时: " + (System.currentTimeMillis() - startTime));
dataOutputStream.close();
socket.close();
inputStream.close();
}
}
OldIOServer _服务端
package com.xizi.zerocopy;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class OldIOServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(7001);
while (true) {
Socket socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
try {
byte[] byteArray = new byte[4096];
while (true) {
int readCount = dataInputStream.read(byteArray, 0, byteArray.length);
if (-1 == readCount) {
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
三. 传统 IO 模型
DMA: direct memory access 直接内存拷贝(不使用 CPU)
四. mmap 优化
- mmap 通过内存映射,将文件映射到内核缓冲区,同时,用户空间可以共享内核空间的数据。这样,在进行网络传输时,就可以减少内核空间到用户空间的拷贝次数。
五. sendFile 优化
- Linux 2.1 版本 提供了 sendFile 函数,其基本原理如下:数据根本不经过用户态,直接从内核缓冲区进入到Socket Buffer,同时,由于和用户态完全无关,就减少了一次上下文切换
- Linux 在 2.4 版本中,做了一些修改,避免了从内核缓冲区拷贝到 Socket buffer 的操作,直接拷贝到协议栈,从而再一次减少了数据拷贝。
- 这里其实有 一次 cpu 拷贝kernel buffer -> socket buffer,但是,拷贝的信息很少,比如 lenght , offset , 消耗低,可以忽略
六. 零拷贝总结
- 我们说零拷贝,是从操作系统的角度来说的。因为内核缓冲区之间,没有数据是重复的(只有 kernel buffer 有一份数据)。
- 零拷贝不仅仅带来更少的数据复制,还能带来其他的性能优势,例如更少的上下文切换,更少的 CPU 缓存伪共享以及无 CPU 校验和计算。
七. mmap 和 sendFile 的区别
- mmap 适合小数据量读写,sendFile 适合大文件传输。
- mmap 需要 4 次上下文切换,3 次数据拷贝;sendFile 需要 3 次上下文切换,最少 2 次数据拷贝。
- sendFile 可以利用 DMA 方式,减少 CPU 拷贝,mmap 则不能(必须从内核拷贝到 Socket 缓冲区)。
八. NIO零拷贝案例(比较原生IO拷贝文件速度)
使用 NIO 零拷贝方式传递(transferTo)一个大文件
NIOZeroCopyClient _服务端
package com.xizi.zerocopy;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
public class NIOZeroCopyClient {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("localhost",7001));
String fileName = "数据结构和算法.zip";
//获取一个文件channel
FileChannel fileChannel = new FileInputStream(fileName).getChannel();
long startTime = System.currentTimeMillis();
//在windows 下一个只能发送8M文件
//transferTo 底层使用零拷贝
long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
System.out.println("发送的总字节数= "+transferCount+ "耗时= "+(System.currentTimeMillis()-startTime));
}
}
NIOZeroCopyServer _服务端
package com.xizi.zerocopy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class NIOZeroCopyServer {
public static void main(String[] args) throws IOException {
InetSocketAddress address = new InetSocketAddress(7001);
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(address);
//创建buffer
ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
while (true){
SocketChannel socketChannel = serverSocketChannel.accept();
int readcount=0;
while (readcount!=-1){
try {
readcount = socketChannel.read(byteBuffer);
} catch (IOException e) {
e.printStackTrace();
}
//将buffer倒带 position=0 mark作废
byteBuffer.rewind();
}
}
}
}