NIO与零拷贝
什么是零拷贝?
零拷贝主要的任务就是避免CPU将数据从一块存储拷贝到另外一块存储,主要就是利用各种零拷贝技术,避免让CPU做大量的数据拷贝任务,减少不必要的拷贝,或者让别的组件来做这一类简单的数据传输任务,让CPU解脱出来专注于别的任务。这样就可以让系统资源的利用更加有效。(一句话,减少甚至避免CPU Copy操作)。
传统的IO拷贝技术
分析:传统的IO拷贝技术需要经过四次拷贝(CPU copy 和 DMA copy),四次的状态转换(用户态和内核态),效率较为低下。
使用mmap优化后的拷贝技术
分析:优化后的拷贝技术虽然减少了一次的CPU copy,效率有所提升,但任然不能称为零拷贝。
使用sendFile技术(一)
分析:数据根本不经过用户态,直接从内核缓冲区进入到Socket Buffer,同时,由于和用户态完全无关,就减少了一次上下文切换
使用sendFile技术(二)
分析:虽然内核缓冲区到socket缓冲区之间任然需要传递一些数据,例如offset,length等,但数据量很小,可以忽略。可以真正意义上称为零拷贝。
mmap和sendFile的区别
- mmap 适合小数据量读写,sendFile 适合大文件传输。
- mmap 需要 4 次上下文切换,3 次数据拷贝;sendFile需要 3 次上下文切换,最少 2 次数据拷贝。
- sendFile 可以利用 DMA 方式,减少 CPU 拷贝,mmap则不能(必须从内核拷贝到 Socket 缓冲区)
使用Java的NIO实现文件的零拷贝
NIO中的transferTo()方法就是基于零拷贝技术实现的,所以我们可以使用transferTo()来实现。
package com.zzq.nio.zerocopy;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
/**
* @author: HP
* @date: 2020/12/25
* @description:
*/
public class NewIOClient {
public static void main(String[] args) throws Exception{
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1",7001));
String filePath="E:\\学习资料文档库\\JVM上篇.zip";
FileChannel fileChannel = new FileInputStream(filePath).getChannel();
long t1 = System.currentTimeMillis();
long size = fileChannel.size();
long postion=0;
//注意:由于tranferTo()方法每次最大只能发送8M,所以需要分段传输
while(size>0){
long count = fileChannel.transferTo(postion, size, socketChannel);
postion+=count;
size-=count;
}
System.out.println("发送的字节数:"+postion+" "+"耗时:"+(System.currentTimeMillis()-t1));
fileChannel.close();
}
}
package com.zzq.nio.zerocopy;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* @author: HP
* @date: 2020/12/25
* @description:
*/
public class NewIOServer {
public static void main(String[] args) throws Exception{
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 (Exception e){
break;
}
byteBuffer.rewind();
}
}
}
}