Netty学习笔记_8(NIO与零拷贝)

15 篇文章 0 订阅

1、零拷贝基本介绍

  • 传统IO是基于数据拷贝操作的,即让数据在操作系统内核地址空间的缓冲区和用户程序地址空间定义的缓冲区进行传输【PS:减少了磁盘IO,但增加了CPU开销( CPU会进行多次冗余拷贝,且在数据拷贝过程中有极大的系统资源浪费 )】
  • 零拷贝是一种避免CPU将数据从一个存储块拷贝到另一块存储的技术【避免数据拷贝+多种操作结合】(所谓“零拷贝”,是没有CPU拷贝)

1.2、传统IO(本地文件数据上传)【4次拷贝,3次切换】

  1. 应用程序调用read()方法,先将数据从磁盘读取到OS内核缓冲区,采用DMA方式进行拷贝,不经过CPU,此时进行一次上下文切换(用户态 —> 内核态)
  2. 应用程序无法直接在内核态操作文件,因此需要将数据从内核缓冲区复制到(用户)应用程序缓冲区进行操作,采用CPU拷贝的方式,涉及一次上下文切换(内核态 —> 用户态)
  3. 将数据从(用户)应用程序缓冲区拷贝到socket Buffer准备进行数据发送,采用CPU拷贝的方式,涉及一次上下文切换(用户态 —> 内核态)
  4. Socket buffer中数据通过DMA方式拷贝到Protocol engine(协议栈)

 

1.3、Mmap优化(内存映射优化)【3次拷贝,3次切换】

  1. Mmap通过内存映射,将文件映射到内核缓冲区,同时,用户空间可以共享内核空间的数据。这样,在进行网络传输时,可以减少内核空间到用户空间的拷贝次数

 

1.4、sendFile优化【3次拷贝,2次切换】

  • Linux2.1提供了sendFile函数:数据不经过用户态,直接从内核缓冲区进入到Socket Buffer,由于与用户态完全无关,减少了一次上下文切换

 

  • Linux2.4版本中,修改:避免了从内核缓冲区拷贝到Socket Buffer的操作,再一次减少了数据拷贝,这里还存在一次CPU拷贝,kernel buffer -> Socket buffer,但拷贝的信息很少(length,offset等描述信息),消耗低,可忽略。

    【2次拷贝,2次切换】

 

1.5、总结

  1. 所谓零拷贝,是从操作系统角度定义的,内核缓冲区之间没有数据重复(只有kernel buffer有一份数据)
  2. 零拷贝:更少的数据复制、更少的上下文切换、更少的CPU缓存伪共享、无CPU校验和计算,等

 

2、Mmap和sendFile的区别

  1. Mmap适合小数据量读写,sendFile适合大文件传输。
  2. Mmap需要3次上下文切换,3次数据拷贝;sendFile需要2次上下文切换,至少2次数据拷贝
  3. sendFile可以利用DMA方式,减少CPU拷贝;mmap不能(必须从内核拷贝到socket缓冲区)

 

3、NIO与零拷贝案例分析

3.1、案例要求:

  1. 使用传统IO方法传递一个大文件
  2. 使用NIO零拷贝方式传递(TransferTo)一个大文件
  3. 看看两种传递方式耗时分别是多少

3.2、实现:

传统IO:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


//Java IO的服务器端
public class OldIOServer {
    public static void main(String[] args) throws IOException {
        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 (readCount == -1){
                        break;
                    }
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }
}
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class OldIOClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 7001);

        String filename = "Gaomon_Windows_Driver.zip";
        FileInputStream inputStream = new FileInputStream(filename);

        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());

        byte[] buffer = new byte[4096];
        long readCount,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();
    }
}

 NIO零拷贝:

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

//服务器端
public class NewIOServer {
    public static void main(String[] args) throws IOException {

        InetSocketAddress address = new InetSocketAddress(7001);

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.bind(address);



        //创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            FileOutputStream fileOutputStream = new FileOutputStream("111.zip");
            FileChannel fileChannel = fileOutputStream.getChannel();

            int readCount = 0;
            while (readCount != -1){
                try {
                    readCount = socketChannel.read(byteBuffer);
//                    System.out.println(readCount);
                    byteBuffer.flip();
                    fileChannel.write(byteBuffer);
                    byteBuffer.clear();
                }catch (Exception e){
                    e.printStackTrace();
                }

                //
                byteBuffer.rewind(); //倒带,position = 0 mark作废
            }
            fileOutputStream.close();
        }
    }
}
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost",7001));

        String filename = "Gaomon_Windows_Driver.zip";

        //得到一个文件的channel
        FileChannel fileChannel = new FileInputStream(filename).getChannel();

        //准备发送
        long startTime = System.currentTimeMillis();
        //在Linux下一个transferTo方法即可完成传输
        //在window下一次调用transferTo只能发送8m文件,需要分段传输
        long p = 0;
        long add = 0;
        while (p < fileChannel.size()){
            long transforlongth = fileChannel.transferTo(p, 1024*1024*1, socketChannel);
            p = p + 1024*1024*1;
            add += transforlongth;
            System.out.println(p);

        }
        System.out.println("传输总字节数 = " + fileChannel.size() + " 耗时:"+(System.currentTimeMillis() - startTime));
        System.out.println(add);
        //fileChannel.transferTo()
        fileChannel.close();
        socketChannel.close();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值