绑定完请刷新页面
取消
刷新

分享好友

×
取消 复制
程序员:java NIO模型,三大核心原理,不防来看看
2019-12-12 09:52:08

NIO

(1)基本介绍

1)Java NIO全程 java non-blocking IO,是指JDK提供的新API。从JDK1.4开始,Java提供了一系列改进的输入/输出的新特性,被统称为NIO,是同步非阻塞的

2)NIO相关类都被放在java.nio包及子包下,并且对原java.io包中的很多类进行改写

3)NIO有三大核心部分:Channel(通道),Buffer(缓冲区),Selector(选择器)

4)NIO是面向缓冲区,或者面向块编程的。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式高伸缩性网络

5)Java NIO的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是保持线程阻塞,所以直至数据变的可以读取之前,该线程可以继续做其它的事情。非阻塞也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情

6)HTTP2.0使用了多路复用的技术,做到同一个连接并发处理多个请求,并且并发请求的数量比HTTP1.1大了好几个数量级

(2)NIO和BIO的比较

1)BIO以流的方式处理数据,而NIO以块的方式处理数据,块I/O的效率比流I/O高很多

2)BIO是阻塞的,NIO是非阻塞的

3)BIO基于字节流和字符流进行操作,而NIO基于Channel(通道)和Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。Selector(选择器)用于监听多个通道的时间(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道

(3)NIO三大核心原理

每个channel都会对应一个Buffer

2)Selector 对应一个线程, 一个线程对应多个channel(连接)

3)该图反应了有三个channel注册到该selector//程序

4)程序切换到哪个channel是由事件决定的,Event就是一个重要的概念

5)Selector 会根据不同的事件,在各个通道上切换

6)Buffer 就是一个内存块 , 底层是有一个数组

7)数据的读取写入是通过Buffer,这个和BIO,BIO中或者是输入流,或者是输出流, 不能双向,但是 NIO 的 Buffer 是可以读也可以写, 需要 flip 方法切换。channel 是双向的, 可以返回底层操作系统的情况, 比如 Linux ,底层的操作系统通道就是双向的

缓冲区(Buffer)

(1)基本介绍

缓冲区(Buffer):缓冲区本质上是一个可以读写数据的内存块,可以理解成是一个容器对象(含数组),该对象提供了一组方法,可以更轻松地使用内存块,缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况。Channel 提供从文件、网络读取数据的渠道,但是读取或写入的数据都必须经由 Buffer

2)Buffer及其子类

1)在 NIO 中,Buffer 是一个顶层父类,它是一个抽象类, 类的层级关系图:

2)Buffer类定义了所有的缓冲区都具有的四个属性来提供关于其所包含的数据元素的信息:

常用方法

 通道(Channel)

(1)基本介绍

NIO的通道类似于流,但有些区别如下:

通道可以同时进行读写,而流只能读或者写

通道可以实现异步读写数据

通道可以从缓冲读数据,也可以写数据到缓冲

BIO中的stream是单向的,例如FileInputStream对象只能进行读取数据的操作,而NIO中的通道(Channel)是双向的,可以读操作,也可以写操作

常见的Channel类有:FileChannel、DatagramChannel、ServerSocketChannel和SocketChannel。

FileChannel用于文件的数据读写,DatagramChannel用于UDP的数据读写,ServerSocketChannel和SocketChannel用于TCP的数据读写

(2)FileChannel

(3)案例1-本地文件写数据

public class NIOFileChannel01 {

public static void main(String[] args) throws Exception{

String str = "hello,NIO";

//创建一个输出流->channel

FileOutputStream fileOutputStream = new FileOutputStream("/Users/apple/学习/study/test01.txt");

//通过 fileOutputStream 获取 对应的 FileChannel

//这个 fileChannel 真实 类型是 FileChannelImpl

FileChannel fileChannel = fileOutputStream.getChannel();

//创建一个缓冲区 ByteBuffer

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

//将 str 放入 byteBuffer

byteBuffer.put(str.getBytes());

//对byteBuffer 进行flip

byteBuffer.flip();

//将byteBuffer 数据写入到 fileChannel

fileChannel.write(byteBuffer);

fileOutputStream.close();

}

}

(4)案例2-本地文件读数据

public class NIOFileChannel02 {

public static void main(String[] args) throws Exception {

//创建文件的输入流

File file = new File("/Users/apple/学习/study/test01.txt");

FileInputStream fileInputStream = new FileInputStream(file);

//通过fileInputStream 获取对应的FileChannel -> 实际类型 FileChannelImpl

FileChannel fileChannel = fileInputStream.getChannel();

//创建缓冲区

ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

//将通道的数据读入到Buffer

fileChannel.read(byteBuffer);

//将byteBuffer 的 字节数据 转成String

System.out.println(new String(byteBuffer.array()));

fileInputStream.close();

}

}

(5)案例3-使用Buffer完成文件的读取、写入

public class NIOFileChannel03 {

public static void main(String[] args) throws Exception {

FileInputStream fileInputStream = new FileInputStream("1.txt");

FileChannel fileChannel01 = fileInputStream.getChannel();

FileOutputStream fileOutputStream = new FileOutputStream("2.txt");

FileChannel fileChannel02 = fileOutputStream.getChannel();

ByteBuffer byteBuffer = ByteBuffer.allocate(512);

//循环读取

while (true) {

//这里有一个重要的操作,一定不要忘了

/*

public final Buffer clear() {

position = 0;

limit = capacity;

mark = -1;

return this;

}

*/

byteBuffer.clear(); //清空buffer

int read = fileChannel01.read(byteBuffer);

System.out.println("read =" + read);

//表示读完

if (read == -1) {

break;

}

//将buffer 中的数据写入到 fileChannel02 -- 2.txt

byteBuffer.flip();

fileChannel02.write(byteBuffer);

}

//关闭相关的流

fileInputStream.close();

fileOutputStream.close();

}

}

(6)案例4-拷贝文件 transferFrom 方法

public class NIOFileChannel04 {

public static void main(String[] args) throws Exception {

//创建相关流

FileInputStream fileInputStream = new FileInputStream("a.jpg");

FileOutputStream fileOutputStream = new FileOutputStream("a1.jpg");

//获取各个流对应的fileChannel

FileChannel sourceCh = fileInputStream.getChannel();

FileChannel destCh = fileOutputStream.getChannel();

//使用transferForm完成拷贝

destCh.transferFrom(sourceCh,0,sourceCh.size());

//关闭相关通道和流

sourceCh.close();

destCh.close();

fileInputStream.close();

fileOutputStream.close();

}

}

(7)案例5-零拷贝文件-transferTo文件

零拷贝参考资料:

https://www.cnblogs.com/yibutian/p/9482640.html

http://www.360doc.com/content/19/0528/13/99071_838741319.shtml

public class NewIOClient {

public static void main(String[] args) throws Exception {

String filename = "/Users/apple/password.txt";

//得到一个文件channel

FileChannel fileChannel = new FileInputStream(filename).getChannel();

FileChannel fileChannel1 = new FileOutputStream("/Users/apple/password1.txt").getChannel();

//准备发送

long startTime = System.currentTimeMillis();

//在linux下一个transferTo 方法就可以完成传输

//在windows 下 一次调用 transferTo 只能发送8m,就需要分段传输文件

//transferTo 底层使用到零拷贝

long transferCount = fileChannel.transferTo(0, fileChannel.size(), fileChannel1);

System.out.println("发送的总的字节数 =" + transferCount + " 耗时:" + (System.currentTimeMillis() - startTime));

//关闭

fileChannel.close();

}

}

(8)注意事项和细节

1)ByteBuffer 支持类型化的 put 和 get, put 放入的是什么数据类型,get 就应该使用相应的数据类型来取出,否则可能有 BufferUnderflowException 异常

public class NIOByteBufferPutGet {

public static void main(String[] args) {

//创建一个Buffer

ByteBuffer buffer = ByteBuffer.allocate(64);

//类型化方式放入数据

buffer.putInt(100);

buffer.putLong(9);

buffer.putChar('a');

buffer.putShort((short) 4);

//取出

buffer.flip();

System.out.println();

System.out.println(buffer.getInt());

System.out.println(buffer.getLong());

System.out.println(buffer.getChar());

System.out.println(buffer.getLong());

}

}

2)可以将一个普通Buffer转成只读Buffer

public class ReadOnlyBuffer {

public static void main(String[] args) {

//创建一个buffer

ByteBuffer buffer = ByteBuffer.allocate(64);

for(int i = 0; i < 64; i++) {

buffer.put((byte)i);

}

//读取

buffer.flip();

//得到一个只读的Buffer

ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();

System.out.println(readOnlyBuffer.getClass());

//读取

while (readOnlyBuffer.hasRemaining()) {

System.out.println(readOnlyBuffer.get());

}

readOnlyBuffer.put((byte)100); //ReadOnlyBufferException

}

}

3)NIO 还提供了 MappedByteBuffer, 可以让文件直接在内存(堆外的内存)中进行修改

public class MappedByteBufferTest {

public static void main(String[] args) throws Exception {

RandomAccessFile randomAccessFile = new RandomAccessFile("/Users/apple/学习/study/test01.txt", "rw");

//获取对应的通道

FileChannel channel = randomAccessFile.getChannel();

/**

* 参数1: FileChannel.MapMode.READ_WRITE 使用的读写模式

* 参数2: 0 : 可以直接修改的起始位置

* 参数3: 5: 是映射到内存的大小(不是索引位置) ,即将 1.txt 的多少个字节映射到内存

* 可以直接修改的范围就是 0-5

* 实际类型 DirectByteBuffer

*/

MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);

mappedByteBuffer.put(0, (byte) 'H');

mappedByteBuffer.put(3, (byte) '9');

// mappedByteBuffer.put(5, (byte) 'Y');//IndexOutOfBoundsException

randomAccessFile.close();

System.out.println("修改成功~~");

}

}

4)NIO 还支持 通过多个 Buffer (即 Buffer 数组) 完成读写操作,即 Scattering 和 Gathering

/**

* Scattering:将数据写入到buffer时,可以采用buffer数组,依次写入 [分散]

* Gathering: 从buffer读取数据时,可以采用buffer数组,依次读

*/

public class ScatteringAndGatheringTest {

public static void main(String[] args) throws Exception {

//使用 ServerSocketChannel 和 SocketChannel 网络

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

//绑定端口到socket ,并启动

serverSocketChannel.socket().bind(inetSocketAddress);

//创建buffer数组

ByteBuffer[] byteBuffers = new ByteBuffer[2];

byteBuffers[0] = ByteBuffer.allocate(5);

byteBuffers[1] = ByteBuffer.allocate(3);

//等客户端连接(telnet)

SocketChannel socketChannel = serverSocketChannel.accept();

//假定从客户端接收8个字节

int messageLength = 8;

//循环的读取

while (true) {

int byteRead = 0;

while (byteRead < messageLength) {

long l = socketChannel.read(byteBuffers);

//累计读取的字节数

byteRead += l;

System.out.println("byteRead=" + byteRead);

//使用流打印, 看看当前的这个buffer的position 和 limit

Arrays.stream(byteBuffers).map(buffer -> "position=" + buffer.position() + ", limit=" + buffer.limit()).forEach(System.out::println);

}

//将所有的buffer进行flip

Arrays.asList(byteBuffers).forEach(Buffer::flip);

//将数据读出显示到客户端

long byteWirte = 0;

while (byteWirte < messageLength) {

long l = socketChannel.write(byteBuffers);

byteWirte += l;

}

//将所有的buffer 进行clear

Arrays.asList(byteBuffers).forEach(Buffer::clear);

System.out.println("byteRead:=" + byteRead + " byteWrite=" + byteWirte + ", messageLength" + messageLength);

}

}

}

选择器(Selector)

(1)基本介绍

1)Java的NIO,用非阻塞的IO方式。可以用一个线程,处理多个的客户端连接,就会用到选择器

2)Selector能够检测多个注册的通道上是否有事件发生。如果有事件发生,便获取事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管理多个通道,也就是管理多个连接和请求

3)只有在连接/通道真正有读写事件发生时,才会进行读写,就大大地减少了系统开销,并且不必为每个连接都创建一个线程,不用去维护多个线程

4)避免了多线程之间的上下文切换导致的开销

(2)常用方法

(3)代码示例

NIOServer.java

public class NIOServer {

public static void main(String[] args) throws Exception {

//创建ServerSocketChannel -> ServerSocket

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

//得到一个Selector对象

Selector selector = Selector.open();

//绑定一个端口6666, 在服务器端监听

serverSocketChannel.socket().bind(new InetSocketAddress(6666));

//设置为非阻塞

serverSocketChannel.configureBlocking(false);

//把 serverSocketChannel 注册到 selector 关心 事件为 OP_ACCEPT

serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

System.out.println("注册后的selectionkey 数量=" + selector.keys().size());

//循环等待客户端连接

while (true) {

//这里我们等待1秒,如果没有事件发生, 返回

if (selector.select(1000) == 0) {

System.out.println("服务器等待了1秒,无连接");

continue;

}

//如果返回的>0, 就获取到相关的 selectionKey集合

//1.如果返回的>0, 表示已经获取到关注的事件

//2. selector.selectedKeys() 返回关注事件的集合

// 通过 selectionKeys 反向获取通道

Set<SelectionKey> selectionKeys = selector.selectedKeys();

System.out.println("selectionKeys 数量 = " + selectionKeys.size());

//遍历 Set<SelectionKey>, 使用迭代器遍历

Iterator<SelectionKey> keyIterator = selectionKeys.iterator();

while (keyIterator.hasNext()) {

//获取到SelectionKey

SelectionKey key = keyIterator.next();

//根据key 对应的通道发生的事件做相应处理

//如果是 OP_ACCEPT, 有新的客户端连接

if (key.isAcceptable()) {

//该该客户端生成一个 SocketChannel

SocketChannel socketChannel = serverSocketChannel.accept();

System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode());

//将 SocketChannel 设置为非阻塞

socketChannel.configureBlocking(false);

//将socketChannel 注册到selector, 关注事件为 OP_READ, 同时给socketChannel

//关联一个Buffer

socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));

System.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size()); //2,3,4..

}

//发生 OP_READ

if (key.isReadable()) {

//通过key 反向获取到对应channel

SocketChannel channel = (SocketChannel) key.channel();

//获取到该channel关联的buffer

ByteBuffer buffer = (ByteBuffer) key.attachment();

channel.read(buffer);

System.out.println("form 客户端 " + new String(buffer.array()));

}

//手动从集合中移动当前的selectionKey, 防止重复操作

keyIterator.remove();

}

}

}

}

NIOClient.java

public class NIOClient {

public static void main(String[] args) throws Exception{

//得到一个网络通道

SocketChannel socketChannel = SocketChannel.open();

//设置非阻塞

socketChannel.configureBlocking(false);

//提供服务器端的ip 和 端口

InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

//连接服务器

if (!socketChannel.connect(inetSocketAddress)) {

while (!socketChannel.finishConnect()) {

System.out.println("因为连接需要时间,客户端不会阻塞,可以做其它工作..");

}

}

//...如果连接成功,就发送数据

String str = "hello, Selector~";

//Wraps a byte array into a buffer

ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());

//发送数据,将 buffer 数据写入 channel

socketChannel.write(buffer);

System.in.read();

}

}

(4)SelectionKey

SelectionKey,表示 Selector 和网络通道的注册关系, 共四种:

int OP_ACCEPT:有新的网络连接可以 accept,值为 16

int OP_CONNECT:代表连接已经建立,值为 8

int OP_READ:代表读操作,值为 1

int OP_WRITE:代表写操作,值为 4

相关方法:

分享好友

分享这个小栈给你的朋友们,一起进步吧。

未知元素
创建时间:2019-11-10 22:02:06
未知元素
展开
订阅须知

• 所有用户可根据关注领域订阅专区或所有专区

• 付费订阅:虚拟交易,一经交易不退款;若特殊情况,可3日内客服咨询

• 专区发布评论属默认订阅所评论专区(除付费小栈外)

栈主、嘉宾

查看更多
  • xiechundi
    栈主

小栈成员

查看更多
  • 渔人
  • abc
  • zyl
  • ?
戳我,来吐槽~