《Netty一》
提示: 本材料只做个人学习参考,不作为系统的学习流程,请注意识别!!!
《Netty一》
1. Netty介绍和应用场景
1.1 Netty的介绍
- Netty 是由 JBOSS 提供的一个 Java 开源框架,现为 Github上的独立项目。
- Netty 是一个异步的、基于事件驱动的网络应用框架,用以快速开发高性能、高可靠性的网络 IO 程序。
- Netty主要针对在TCP协议下,面向Clients端的高并发应用,或者Peer-to-Peer场景下的大量数据持续传输的应用。
- Netty本质是一个NIO框架,适用于服务器通讯相关的多种应用场景
- 要透彻理解Netty ,需要先学习NIO ,这样我们才能阅读Netty的源码。
1.2 Netty的应用场景
互联网行业
-
互联网行业:在分布式系统中,各个节点之间需要远程服务调用,高性能的RPC 框架必不可少,Netty 作为异步高性能的通信框架,往往作为基础通信组件被这些 RPC 框架使用。
-
典型的应用有:阿里分布式服务框架 Dubbo 的 RPC 框架使用 Dubbo 协议进行节点间通信,Dubbo 协议默认使用 Netty 作为基础通信组件,用于实现各进程节点之间的内部通信
游戏行业
-
无论是手游服务端还是大型的网络游戏, Java 语言得到了越来越广泛的应用
-
Netty 作为高性能的基础通信组件,提供了 TCP/UDP 和 HTTP 协议栈,方便定制和开发私有协议栈,账号登录服务器
-
地图服务器之间可以方便的通过 Netty 进行高性能的通信
大数据领域
-
经典的 Hadoop 的高性能通信和序列化组件 Avro 的 RPC 框架, 默认采用 Netty 进行跨界点通信
-
它的 Netty Service 基于 Netty 框架二次封装实现。
Netty的应用场景
其它开源项目使用到Netty
网址: https://netty.io/wiki/related-projects.html
1.3 Netty的学习参考资料
2. Java BIO编程
2.1 I/O模型
I/O 模型基本说明
-
I/O 模型简单的理解:就是用什么样的通道进行数据的发送和接收,很大程度上决定了程序通信的性能
-
Java共支持3种网络编程模型/IO模式:BIO、NIO、AIO
-
Java BIO : 同步并阻塞(传统阻塞型),服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销
【简单示意图】
- Java NIO : 同步非阻塞,服务器实现模式为一个线程处理多个请求(连接),即客户端发送的连接请求都会注册到多路复用器上,多路复用器轮询到连接有I/O请求就进行处理
【简单示意图】
- Java AIO(NIO.2) : 异步非阻塞,AIO 引入异步通道的概念,采用了 Proactor 模式,简化了程序编写,有效的请求才启动线程,它的特点是先由操作系统完成后才通知服务端程
2.2 BIO、NIO、AIO适用场景分析
-
BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高, 并发局限于应用中,JDK1.4以前的唯一选择,但程序简单易理解。
-
NIO方式适用于连接数目多且连接比较短(轻操作)的架构,比如聊天服务器,弹幕系统,服务器间通讯等。编程比较复杂,JDK1.4开始支持。
-
AIO方式使用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分调用OS参与并发操作,编程比较复杂,JDK7开始支持。
2.3 Java BIO 基本介绍
-
Java BIO 就是传统的java io 编程,其相关的类和接口在 java.io
-
BIO(blocking I/O) : 同步阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,可以通过线程池机制改善(实现多个客户连接服务器)。
-
BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4以前的唯一选择,程序简单易理解
2.3.1 Java BIO 工作机制
工作原理图
BIO编程简单流程
-
服务器端启动一个ServerSocket
-
客户端启动Socket对服务器进行通信,默认情况下服务器端需要对每个客户建立一个线程与之通讯
-
客户端发出请求后, 先咨询服务器是否有线程响应,如果没有则会等待,或者被拒绝
-
如果有响应,客户端线程会等待请求结束后,在继续执行
2.3.2 Java BIO 应用实例
实例说明:
-
使用BIO模型编写一个服务器端,监听6666端口,当有客户端连接时,就启动一个线程与之通讯。
-
要求使用线程池机制改善,可以连接多个客户端.
-
服务器端可以接收客户端发送的数据(telnet 方式即可)。
-
代码示例
package bio;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @description: BIOServer
* @author: ybl
* @create: 2022-06-10 19:18
* 线程池机制, 思路
* 1. 创建一个线程池
* 2. 如果有客户端连接,就创建一个线程,与之通讯(单独写一个方法)
**/
public class BIOServer {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
//创建ServerSocket
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("服务启动了 ... ");
while (true) {
System.out.println("11 ==> 线程 id = " + Thread.currentThread().getId() + " 名字 = " + Thread.currentThread().getName());
//监听,等待客户端连接
System.out.println("等待连接 ... ");
Socket socket = serverSocket.accept();
System.out.println("连接到了一个客户端");
//创建一个线程,与之通讯(单独写一个方法)
executorService.execute(() -> {
handler(socket);
});
}
}
/**
* 与客户端通讯的逻辑
*
* @param socket
*/
private static void handler(Socket socket) {
try {
System.out.println("22 =====> 线程 id = " + Thread.currentThread().getId() + " 名字 = " + Thread.currentThread().getName());
byte[] bytes = new byte[1024];
//通过socket获取输入流
InputStream inputStream = socket.getInputStream();
//循环读取客户端发送的数据
while (true) {
System.out.println("33 =====> 线程 id = " + Thread.currentThread().getId() + " 名字 = " + Thread.currentThread().getName());
System.out.println("read ......");
int read = inputStream.read(bytes);
if (read != -1) {
//输出客户端发送的数据
System.out.println(new String(bytes, 0, read));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
测试代码:
- 执行main方法
- 打开cmd, telnet 连接
- 按下Ctrl + ] 发送 , 输入 send hello 回车
2.3.3 Java BIO 问题分析
- 每个请求都需要创建独立的线程,与对应的客户端进行数据 Read,业务处理,数据 Write 。
- 当并发数较大时,需要创建大量线程来处理连接,系统资源占用较大。
- 连接建立后,如果当前线程暂时没有数据可读,则线程就阻塞在Read 操作上,造成线程资源浪费
2.4 Java NIO编程
2.4.1 Java NIO 基本介绍
-
Java NIO 全称 java non-blocking IO,是指 JDK 提供的新 API。从 JDK1.4 开始,Java 提供了一系列改进的输入/输出 的新特性,被统称为 NIO(即 New IO),是同步非阻塞的
-
NIO 相关类都被放在 java.nio 包及子包下,并且对原 java.io 包中的很多类进行改写。
-
NIO 有三大核心部分:Channel(通道),Buffer(缓冲区), Selector(选择器)
-
NIO 是面向缓冲区 ,或者面向块编程的。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式的高伸缩性网络
-
Java NIO的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是保持线程阻塞,所以直至数据变的可以读取之前,该线程可以继续做其他的事情。 非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情。【后面有案例说明】
-
通俗理解:NIO是可以做到用一个线程来处理多个操作的。假设有10000个请求过来, 根据实际情况,可以分配50或者100个线程来处理。不像之前的阻塞IO那样,非得分 配10000个。
-
HTTP2.0使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求 的数量比HTTP1.1大了好几个数量级。
-
代码说明
package nio;
import java.nio.IntBuffer;
/**
* @description: 举例说明Buffer的使用
* @author: ybl
* @create: 2022-06-10 19:56
**/
public class BasicBuffer {
public static void main(String[] args) {
//创建一个Buffer, 大小为5, 可以存放5个int
IntBuffer intBuffer = IntBuffer.allocate(5);
//存放数据
for (int i = 0; i < intBuffer.capacity(); i++) {
intBuffer.put(i * 2);
}
//从buffer中读取数据
//将buffer转换, 读写切换
intBuffer.flip();
while (intBuffer.hasRemaining()) {
System.out.println(intBuffer.get());
}
}
}
2.4.2 NIO 和 BIO 的比较
-
BIO 以流的方式处理数据,而 NIO 以块的方式处理数据,块 I/O 的效率比流 I/O 高很多
-
BIO 是阻塞的,NIO 则是非阻塞的
-
BIO基于字节流和字符流进行操作,而 NIO 基于 Channel(通道)和 Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。 Selector(选择器)用于监听多个通道的事件(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道
2.4.3 NIO 三大核心原理示意图
一张图描述NIO 的 Selector 、 Channel 和 Buffer 的关系
关系图的说明:
-
每个channel 都会对应一个Buffer
-
Selector 对应一个线程, 一个线程对应多个channel(连接)
-
该图反应了有三个channel 注册到 该selector
-
程序切换到哪个channel 是有事件决定的, Event 就是一个重要的概念
-
Selector 会根据不同的事件,在各个通道上切换
-
Buffer 就是一个内存块 , 底层是有一个数组
-
数据的读取写入是通过Buffer, 这个和BIO不同, BIO 中要么是输入流,或者是输出流, 不能双向,但是NIO的Buffer 是可以读也可以写, 需要 flip 方法切换
-
channel 是双向的, 可以返回底层操作系统的情况, 比如Linux , 底层的操作系统通道就是双向的
2.4.4 缓冲区(Buffer)
2.4.4.1 基本介绍
缓冲区(Buffer):缓冲区本质上是一个可以读写数据的内存块,可以理解成是一个容器对象(含数组),该对象提供了一组方法,可以更轻松地使用内存块,缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况。Channel 提供从文件、 网络读取数据的渠道,但是读取或写入的数据都必须经由 Buffer,
如图: 【后面举例说 明】
2.4.4.2 Buffer 类及其子类
- 在 NIO 中,Buffer 是一个顶层父类,它是一个抽象类, 类的层级关系图:
常用Buffer子类一览
- ByteBuffer,存储字节数据到缓冲区
- ShortBuffer,存储字符串数据到缓冲区
- CharBuffer,存储字符数据到缓冲区
- IntBuffer,存储整数数据到缓冲区
- LongBuffer,存储长整型数据到缓冲区
- DoubleBuffer,存储小数到缓冲区
- FloatBuffer,存储小数到缓冲区
-
Buffer类定义了所有的缓冲区都具有的四个属性来提供关于其所包含的数据元素的信息
-
Buffer类相关方法 一览
public abstract class Buffer {
//JDK1.4时,引入的api
public final int capacity( )//返回此缓冲区的容量
public final int position( )//返回此缓冲区的位置
public final Buffer position (int newPositio)//设置此缓冲区的位置
public final int limit( )//返回此缓冲区的限制
public final Buffer limit (int newLimit)//设置此缓冲区的限制
public final Buffer mark( )//在此缓冲区的位置设置标记
public final Buffer reset( )//将此缓冲区的位置重置为以前标记的位置
public final Buffer clear( )//清除此缓冲区, 即将各个标记恢复到初始状态,但是数据并没有真正擦除, 后面操作会覆盖
public final Buffer flip( )//反转此缓冲区
public final Buffer rewind( )//重绕此缓冲区
public final int remaining( )//返回当前位置与限制之间的元素数
public final boolean hasRemaining( )//告知在当前位置和限制之间是否有元素
public abstract boolean isReadOnly( );//告知此缓冲区是否为只读缓冲区
//JDK1.6时引入的api
public abstract boolean hasArray();//告知此缓冲区是否具有可访问的底层实现数组
public abstract Object array();//返回此缓冲区的底层实现数组
public abstract int arrayOffset();//返回此缓冲区的底层实现数组中第一个缓冲区元素的偏移量
public abstract boolean isDirect();//告知此缓冲区是否为直接缓冲区
}
2.4.4.3 ByteBuffer
从前面可以看出对于 Java 中的基本数据类型(boolean除外),都有一个 Buffer 类型与之相对应,最常用的自然是ByteBuffer 类(二进制数据),该类的主要方法如下:
public abstract class ByteBuffer {
//缓冲区创建相关api
public static ByteBuffer allocateDirect(int capacity)//创建直接缓冲区
public static ByteBuffer allocate(int capacity)//设置缓冲区的初始容量
public static ByteBuffer wrap(byte[] array)//把一个数组放到缓冲区中使用
//构造初始化位置offset和上界length的缓冲区
public static ByteBuffer wrap(byte[] array,int offset, int length)
//缓存区存取相关API
public abstract byte get( );//从当前位置position上get,get之后,position会自动+1
public abstract byte get (int index);//从绝对位置get
public abstract ByteBuffer put (byte b);//从当前位置上添加,put之后,position会自动+1
public abstract ByteBuffer put (int index, byte b);//从绝对位置上put
}
2.4.5 通道(Channel)
2.4.5.1 基本介绍
- NIO的通道类似于流,但有些区别如下:
- 通道可以同时进行读写,而流只能读或者只能写
- 通道可以实现异步读写数据
- 通道可以从缓冲读数据,也可以写数据到缓冲
-
BIO 中的 stream 是单向的,例如 FileInputStream 对象只能进行读取数据的操作,而 NIO 中的通道 (Channel)是双向的,可以读操作,也可以写操作。
-
Channel在NIO中是一个接口 public interface Channel extends Closeable{}
-
常用的 Channel 类有:FileChannel、 DatagramChannel、ServerSocketChannel 和 SocketChannel。【ServerSocketChanne 类似 ServerSocket , SocketChannel 类似 Socket】
-
FileChannel 用于文件的数据读写, DatagramChannel 用于 UDP 的数据读写, ServerSocketChannel 和 SocketChannel 用于 TCP 的数据读写
2.4.5.2 FileChannel 类
FileChannel主要用来对本地文件进行 IO 操作,常见的方法有
-
public int read(ByteBuffer dst) ,从通道读取数据并放到缓冲区中
-
public int write(ByteBuffer src) ,把缓冲区的数据写到通道中
-
public long transferFrom(ReadableByteChannel src, long position, long count),从目标通道中复制数据到当前通道
-
public long transferTo(long position, long count, WritableByteChannel target),把数据从当前通道复制给目标通道
应用实例 1-本地文件写数据
实例要求:
-
使用前面学习后的ByteBuffer(缓冲) 和 FileChannel(通道), 将文本写入 到file01.txt 中
-
文件不存在就创建
-
代码演示
package nio;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @description: fileChannel测试一
* @author: ybl
* @create: 2022-06-10 20:37
**/
public class NIOFileChannel01 {
public static void main(String[] args) throws Exception {
String str = "你好 netty";
//创建一个输出流 -> channel
FileInputStream fileOutputStream = new FileOutputStream("d:\\file01.txt");
//通过fileInputStream 获取 FileChannel(实际类型是子类FileChannelImpl)
FileChannel fileChannel = fileOutputStream.getChannel();
//创建一个缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//将str放入byteBuffer
byteBuffer.put(str.getBytes());
byteBuffer.flip();
//将byteBuffer数据写入到fileChannel
fileChannel.write(byteBuffer);
fileInputStream.close();
}
}
应用实例 2-本地文件读数据
实例要求:
-
使用前面学习后的ByteBuffer(缓冲) 和 FileChannel(通道), 将 file01.txt 中的数据读 入到程序,并显示在控制台屏幕
-
假定文件已经存在
-
代码演示
package nio;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @description: fileChannel测试二
* @author: ybl
* @create: 2022-06-13 20:20
**/
public class NIOFileChannel02 {
public static void main(String[] args) throws Exception {
//创建文件的输入流
File file = new File("d:\\file01.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();
}
}
应用实例 3-使用一个Buffer完成文件读写(拷贝)
实例要求:
-
使用 FileChannel(通道) 和 方法 read , write,完成文件的拷贝
-
拷贝一个文本文件 1.txt , 放在项目下即可
-
代码演示
package nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @description: fileChannel测试三
* @author: ybl
* @create: 2022-06-13 20:13
**/
public class NIOFileChannel03 {
public static void main(String[] args) throws Exception {
//创建文件的输入流
File file1 = new File("d:\\file01.txt");
FileInputStream fileInputStream = new FileInputStream(file1);
//通过fileInputStream获取对应的FileChannel -> 实际类型FileChannelImpl
FileChannel fileChannel01 = fileInputStream.getChannel();
//创建文件的输入流
File file2 = new File("d:\\file02.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file2);
//通过fileOutputStream获取对应的FileChannel -> 实际类型FileChannelImpl
FileChannel fileChannel02 = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
//循环读取
while (true) {
byteBuffer.clear();
int read = fileChannel01.read(byteBuffer);
if (read == -1) {//读完
break;
}
//将buffer中的数据写入到file2中
byteBuffer.flip();
fileChannel02.write(byteBuffer);
}
fileChannel01.close();
fileChannel02.close();
fileInputStream.close();
fileOutputStream.close();
}
}
应用实例 4-拷贝文件transferFrom 方法
实例要求:
-
使用 FileChannel(通道) 和 方法 transferFrom ,完成文件的拷贝
-
拷贝一张图片
-
代码演示
package nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @description: fileChannel测试三
* @author: ybl
* @create: 2022-06-13 20:19
**/
public class NIOFileChannel04 {
public static void main(String[] args) throws Exception {
//创建文件的输入流
FileInputStream fileInputStream = new FileInputStream("d:\\a.jpg");
FileOutputStream fileOutputStream = new FileOutputStream("d:\\b.jpg");
//创建Channel
FileChannel sourceCh = fileInputStream.getChannel();
FileChannel destCh = fileOutputStream.getChannel();
//使用transferFrom
destCh.transferFrom(sourceCh, 0, sourceCh.size());
sourceCh.close();
destCh.close();
fileInputStream.close();
fileOutputStream.close();
}
}
2.4.5.3 关于Buffer 和 Channel的注意事项和细节
-
ByteBuffer 支持类型化的put 和 get, put 放入的是什么数据类型,get就应该使用相应的数据类型来取出,否则可能有 BufferUnderflowException 异常。
-
可以将一个普通Buffer 转成只读Buffer
[举例说明]
package nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @description: fileChannel测试三
* @author: ybl
* @create: 2022-06-13 21:13
**/
public class ReadOnlyBuffer {
public static void main(String[] args) throws Exception {
//创建一个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());
}
//ReadOnlyBufferException
readOnlyBuffer.put((byte)100);
}
}
- NIO 还提供了 MappedByteBuffer, 可以让文件直接在内存(堆外的内存)中进行修改, 而如何同步到文件由NIO 来完成.
[举例说明]
package nio;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* @description: MappedByteBuffer可以直接在内存中修改(堆外内存), 系统不需要拷贝一次
* @author: ybl
* @create: 2022-06-14 19:24
**/
public class MappedByteBufferTest {
public static void main(String[] args) throws Exception {
//获取对应的通道
RandomAccessFile randomAccessFile = new RandomAccessFile("1.txt", "rw");
FileChannel channel = randomAccessFile.getChannel();
/**
* 参数一: FileChannel.MapMode.READ_WRITE 使用的是读写模式
* 参数二: 0 可以直接修改的起始位置
* 参数三: 5 映射到内存的大小(不是索引位置),即将1.txt的多少个字节映射到内存
*
* 实际类型是DirectByteBuffer
*/
MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
mappedByteBuffer.put(0, (byte) 'H');
mappedByteBuffer.put(3, (byte) '9');
mappedByteBuffer.put(0, (byte) 'H');
randomAccessFile.close();
System.out.println("修改成功~~");
}
}
- 前面我们讲的读写操作,都是通过一个Buffer 完成的,NIO 还支持通过多个 Buffer (即 Buffer 数组) 完成读写操作,即 Scattering 和 Gathering
[举例说明]
package nio;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
/**
* @description: 多个 Buffer (即 Buffer 数组) 完成读写操作
* @author: ybl
* @create: 2022-06-14 19:43
**/
public class ScatteringAndGatheringTest {
public static void main(String[] args) throws Exception {
//使用ServerSocketChannel 和
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();
int messageLength = 8;//假定从客户端接收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.asList(byteBuffers).stream().map(buffer -> "==> position = " + buffer.position() + ", limit = " + buffer.limit()).forEach(System.out::println);
}
//将所有的buffer进行flip
Arrays.asList(byteBuffers).forEach(buffer -> buffer.flip());
//将数据读出显示到客户端
long byteWirte = 0;
while (byteWirte < messageLength) {
long l = socketChannel.write(byteBuffers);
byteWirte += 1;
}
//将所有的buffer进行clear
Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());
System.out.println("byteRead = " + byteRead + ", byteWirte = " + byteWirte + ", messageLength = " + messageLength);
}
}
}
2.4.6 选择器(Selector)
2.4.6.1 基本介绍
-
Java 的 NIO,用非阻塞的 IO 方式。可以用一个线程,处理多个的客户端连接,就会使用到Selector(选择器)
-
Selector 能够检测多个注册的通道上是否有事件发生(注意:多个Channel以事件的方式可以注册到同一个Selector),如果有事件发生,便获取事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管理多个通道,也就是管理多个连接和请求。
-
只有在连接/通道真正有读写事件发生时,才会进行读写,就大大地减少了系统开销,并且不必为每个连接都创建一个线程,不用去维护多个线程
-
避免了多线程之间的上下文切换导致的开销
2.4.6.2 Selector示意图和特点说明
特点再说明:
-
Netty 的 IO 线程 NioEventLoop 聚合了 Selector(选择器, 也叫多路复用器),可以同时并发处理成百上千个客户端连接。
-
当线程从某客户端 Socket 通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。
-
线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO 操作,所以单独的线程可以管理多个输入和输出通道。
-
由于读写操作都是非阻塞的,这就可以充分提升 IO 线程的运行效率,避免由于频繁 I/O 阻塞导致的线程挂起。
-
一个 I/O 线程可以并发处理 N 个客户端连接和读写操作,这从根本上解决了传统同步阻塞 I/O 一连接一线程模型,架构的性能、弹性伸缩能力和可靠性都得到了极大的提升。
2.4.6.3 Selector类相关方法
Selector 类是一个抽象类, 常用方法和说明如下:
public abstract class Selector implements Closeable {
public static Selector open();//得到一个选择器对象
public int select(long timeout);//监控所有注册的通道,当其 中有 IO 操作可以进行时,将 对应的 SelectionKey 加入到内部集合中并返回,参数用来 设置超时时间
public Set<SelectionKey> selectedKeys();//从内部集合中得 到所有的 SelectionKey
}
2.4.6.4 注意事项
-
NIO中的 ServerSocketChannel功能类似ServerSocket,SocketChannel功能类似Socket
-
selector 相关方法说明
- selector.select()//阻塞
- selector.select(1000);//阻塞1000毫秒,在1000毫秒后返回
- selector.wakeup();//唤醒selector
- selector.selectNow();//不阻塞,立马返还
2.4.7 NIO 非阻塞 网络编程原理分析图
NIO 非阻塞网络编程相关的(Selector、SelectionKey、 ServerScoketChannel和SocketChannel) 关系梳理图
对图说明:
- 当客户端连接时,会通过 ServerSocketChannel 得到 SocketChannel
- Selector 进行监听 select 方法, 返回有事件发生的通道的个数.
- 将socketChannel注册到Selector上, register(Selector sel, int ops), 一个 selector上可以注册多个SocketChannel
- 注册后返回一个 SelectionKey, 会和该 Selector 关联(集合)
- 进一步得到各个 SelectionKey (有事件发生)
- 在通过 SelectionKey 反向获取 SocketChannel , 方法 channel()
- 可以通过得到的 channel , 完成业务处理
- 代码撑腰。。。
2.4.7.1 NIO 非阻塞 网络编程快速入门
案例要求:
- 编写一个 NIO 入门案例,实现服务器端和客户端之间的数据简单通讯(非阻塞)
- 目的:理解NIO非阻塞网络编程机制
- 代码演示
服务端
package nio;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
* @description: 非阻塞 网络编程快速入门 服务端
* @author: ybl
* @create: 2022-06-14 19:39
**/
public class NIOServer {
public static void main(String[] args) throws Exception {
//创建 ServerSocketChannel -> SocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//得到一个Selector对象
Selector selector = Selector.open();
//绑定一个端口6666,在服务端监听
serverSocketChannel.socket().bind(new InetSocketAddress(6666));
//设置为非阻塞
serverSocketChannel.configureBlocking(false);
//把serverSocketChannel注册到Selector,关心事件为SelectionKey.OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//循环等待客户端连接
while (true) {
//这里我们等待一秒,如果没有事件发生就返回
if (selector.select(1000) == 0) {//没有事件发生
System.out.println("服务器等待了一秒,无连接~~");
continue;
}
/**
* 1. 如果>0,表示已经获取到关注的事件
* 2. selector.selectedKeys() 返回关注事件的集合
* 3. 通过selectionKeys反向获取通道
*/
Set<SelectionKey> selectionKeys = selector.selectedKeys();
//使用迭代器遍历Set<SelectionKey>
Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
while (keyIterator.hasNext()) {
//获取SelectionKey
SelectionKey key = keyIterator.next();
//根据key对应的通道发生的事件作出相应的处理
if (key.isAcceptable()) {//如果是OP_ACCEPT,表示有新的客户端连接
//该客户端生成一个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));
}
if (key.isReadable()) {//发生OP_READ事件
//通过key 获取到 channel
SocketChannel channel = (SocketChannel) key.channel();
//获取channel 关联的buffer
ByteBuffer buffer = (ByteBuffer) key.attachment();
channel.read(buffer);
System.out.println("from 客户端: " + new String(buffer.array()));
}
//手动移除当前的selectionKey,防止重复操作
keyIterator.remove();
}
}
}
}
客户端
package nio;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* @description: 非阻塞 网络编程快速入门 客户端
* @author: ybl
* @create: 2022-06-14 19:59
**/
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,netty网络编程";
ByteBuffer buffer = ByteBuffer.wrap(str.getBytes(StandardCharsets.UTF_8));
//发送数据,将buffer数据写入到channel
socketChannel.write(buffer);
System.in.read();
}
}
2.4.7.2 SelectionKey
- SelectionKey,表示 Selector 和网络通道的注册关系, 共四种:
int OP_ACCEPT:有新的网络连接可以 accept,值为 16
int OP_CONNECT:代表连接已经建立,值为 8
int OP_READ:代表读操作,值为 1
int OP_WRITE:代表写操作,值为 4
源码中:
public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;
- SelectionKey相关方法
public abstract class SelectionKey {
public abstract Selector selector();//得到与之关联的 Selector 对象
public abstract SelectableChannel channel();//得到与之关 联的通道
public final Object attachment();//得到与之关联的共享数 据
public abstract SelectionKey interestOps(int ops);//设置或改 变监听事件
public final boolean isAcceptable();//是否可以 accept
public final boolean isReadable();//是否可以读
public final boolean isWritable();//是否可以写
}
2.4.7.3 ServerSocketChannel
-
ServerSocketChannel 在服务器端监听新的客户端 Socket 连接
-
相关方法如下
public abstract class ServerSocketChannel extends AbstractSelectableChannel implements NetworkChannel{
public static ServerSocketChannel open()//得到一个 ServerSocketChannel 通道
public final ServerSocketChannel bind(SocketAddress local)//设置服务器端端口 号
public final SelectableChannel configureBlocking(boolean block)//设置阻塞或非 阻塞模式,取值 false 表示采用非阻塞模式
public SocketChannel accept()//接受一个连接,返回代表这个连接的通道对象
public final SelectionKey register(Selector sel, int ops)//注册一个选择器并设置 监听事件
}
2.4.7.4 SocketChannel
-
SocketChannel,网络 IO 通道,具体负责进行读写操作。NIO 把缓冲区的数据写入通 道,或者把通道里的数据读到缓冲区。
-
相关方法如下
public abstract class SocketChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel{
public static SocketChannel open();//得到一个 SocketChannel 通道
public final SelectableChannel configureBlocking(boolean block);//设置阻塞或非阻塞 模式,取值 false 表示采用非阻塞模式
public boolean connect(SocketAddress remote);//连接服务器
public boolean finishConnect();//如果上面的方法连接失败,接下来就要通过该方法 完成连接操作
public int write(ByteBuffer src);//往通道里写数据
public int read(ByteBuffer dst);//从通道里读数据
public final SelectionKey register(Selector sel, int ops, Object att);//注册一个选择器并 设置监听事件,最后一个参数可以设置共享数据
public final void close();//关闭通道
}
2.4.7.5 NIO 网络编程应用实例-群聊系统
实例要求:
-
编写一个 NIO 群聊系统,实现服务器 端和客户端之间的数据简单通讯(非阻塞)
-
实现多人群聊
-
服务器端:可以监测用户上线, 离线, 并实现消息转发功能
-
客户端:通过channel 可以无阻塞发送 消息给其它所有用户,同时可以接受 其它用户发送的消息(有服务器转发得到)
-
目的:进一步理解NIO非阻塞网络编程机制
-
代码演示
服务端
package nio.chat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
/**
* @description: 群聊服务端
* @author: ybl
* @create: 2022-06-15 19:34
**/
public class GroupChatServer {
//定义属性
private Selector selector;
private ServerSocketChannel listenChannel;
private static final int PORT = 6667;
//初始化
public GroupChatServer() {
try {
//得到选择器
selector = Selector.open();
listenChannel = ServerSocketChannel.open();
listenChannel.socket().bind(new InetSocketAddress(PORT));
//设置非阻塞
listenChannel.configureBlocking(false);
//注册到selector
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 监听
*/
public void listen() {
try {
while (true) {
int count = selector.select();
if (count > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel sc = listenChannel.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
System.out.println(sc.getRemoteAddress() + " 上线~~~");
}
if (key.isReadable()) {
readData(key);
}
}
iterator.remove();
} else {
System.out.println("等待...");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取客户端消息
*
* @param key
*/
private void readData(SelectionKey key) {
SocketChannel channel = null;
try {
channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int count = channel.read(buffer);
if (count > 0) {
//把缓冲区的数据转换成字符串
String msg = new String(buffer.array());
System.out.println(msg);
System.out.println("from 客户端: " + msg);
//向其他客户端发送消息
sendToOther(msg, channel);
}
} catch (Exception e) {
try {
System.out.println(channel.getRemoteAddress() + "离线了o(╥﹏╥)o");
//取消注册
key.cancel();
//关闭通道
channel.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
e.printStackTrace();
}
}
/**
* 转发消息给其他客户端
*
* @param msg
* @param self
*/
private void sendToOther(String msg, SocketChannel self) throws IOException {
System.out.println("消息转发中.......");
//遍历所有的SocketChannel,排除自己
for (SelectionKey key : selector.keys()) {
SelectableChannel targetChannel = key.channel();
if (targetChannel instanceof SocketChannel && targetChannel != self) {
SocketChannel dest = (SocketChannel) targetChannel;
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
dest.write(buffer);
}
}
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
}
客户端
package nio.chat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
/**
* @description: 群聊客户端
* @author: ybl
* @create: 2022-06-15 20:00
**/
public class GroupChatClient {
//定义属性
private final String HOST = "127.0.0.1";
private final int PORT = 6667;
private Selector selector;
private SocketChannel socketChannel;
private String userName;
//初始化
public GroupChatClient() {
try {
//得到选择器
selector = Selector.open();
socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
userName = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(userName + " is OK ~~ ");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 向服务器发送数据
*
* @param info
*/
public void sendInfo(String info) {
info = userName + " 说 " + info;
try {
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从服务器读取数据
*/
public void readInfo() {
try {
int readChannels = selector.select();
if (readChannels > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
sc.read(buffer);
String msg = new String(buffer.array());
System.out.println(msg.trim());
}
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
GroupChatClient chatClient = new GroupChatClient();
new Thread(()->{
while(true){
chatClient.readInfo();
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String s = scanner.nextLine();
chatClient.sendInfo(s);
}
}
}
2.4.8 NIO与零拷贝
2.4.8.1 零拷贝基本介绍
-
零拷贝是网络编程的关键,很多性能优化都离不开。
-
在 Java 程序中,常用的零拷贝有 mmap(内存映射) 和 sendFile。那么,他们在 OS 里,到底是怎么样的一个的设计?我们分析 mmap 和 sendFile 这两个零拷贝
-
另外我们看下NIO 中如何使用零拷贝
2.4.8.2 NIO与零拷贝
传统IO数据读写
- Java 传统 IO 和 网络编程的一段代码
传统IOS示意图
mmap 优化
-
mmap 通过内存映射,将文件映射到内核缓冲区,同时,用户空间可以共享内核空间的数据。这样,在进行网络传输时,就可以减少内核空间到用户控件的拷贝次数。
-
mmap示意图
sendFile 优化
-
Linux 2.1 版本提供了sendFile 函数,其基本原理如下:数据根本不经过用户态,直接从内核缓冲区进入到 Socket Buffer,同时,由于和用户态完全无关,就减少了一次上下文切换
-
示意图和小结 提示:零拷贝从操作系统角 度,是没有cpu 拷贝
-
Linux 在 2.4 版本中,做了一些修改,避免了从内核缓冲区拷贝到 Socket buffer 的操作,直接拷贝到 协议栈,从而再一次减少了数据拷贝。具体如下图
这里其实有 一次cpu 拷贝 kernel buffer -> socket buffer 但是,拷贝的信息很少,比如 lenght , offset , 消耗低,可以忽略
2.4.8.3 零拷贝的再次理解
-
我们说零拷贝,是从操作系统的角度来说的。因为内核缓冲区之间,没有数据是重复的(只有 kernel buffer 有一份数据)。
-
零拷贝不仅仅带来更少的数据复制,还能带来其他的性能优势,例如更少的上下文切换,更少的CPU 缓存伪共享以及无CPU 校验和计算。
mmap 和 sendFile 的区别
-
mmap 适合小数据量读写,sendFile 适合大文件传输。
-
mmap 需要 4 次上下文切换,3 次数据拷贝;sendFile 需要 3 次上下文切换,最 少 2 次数据拷贝。
-
sendFile 可以利用 DMA 方式,减少 CPU 拷贝,mmap 则不能(必须从内核拷贝 到 Socket 缓冲区)。
2.4.8.4 NIO 零拷贝案例
案例要求:
-
使用传统的IO 方法传递一个大文件
-
使用NIO 零拷贝方式传递(transferTo)一个大文件
package nio.zerocopy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* @description: 零拷贝服务器端
* @author: ybl
* @create: 2022-06-16 20:05
**/
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);
ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
while (true) {
SocketChannel socketChannel = serverSocketChannel.accept();
int readCount = 0;
while (-1 != readCount) {
try {
readCount = socketChannel.read(byteBuffer);
} catch (IOException e) {
break;
}
byteBuffer.rewind();//position = 0; mark = -1;
}
}
}
}
package nio.zerocopy;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
/**
* @description: 零拷贝客户端
* @author: ybl
* @create: 2022-06-16 20:28
**/
public class NewIOClient {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 7001));
String fileName = "a.txt";
FileChannel fileChannel = new FileInputStream(fileName).getChannel();
//准备发送
long start = System.currentTimeMillis();
//linux 一个transferTo 方法就可以完成传输
//windows一次调用只能发送8m,大文件需要分段传输
//transferTo底层使用了零拷贝
long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
System.out.println("发送的总字节数 = " + transferCount + " 耗时: " + (System.currentTimeMillis() - start));
fileChannel.close();
}
}
2.4.9 Java AIO 基本介绍
-
JDK 7 引入了 Asynchronous I/O,即 AIO。在进行 I/O 编程中,常用到两种模式: Reactor和 Proactor。Java 的 NIO 就是 Reactor,当有事件触发时,服务器端得到通知,进行相应的处理
-
AIO 即 NIO2.0,叫做异步不阻塞的 IO。AIO 引入异步通道的概念,采用了 Proactor 模式,简化了程序编写,有效的请求才启动线程,它的特点是先由操作 系统完成后才通知服务端程序启动线程去处理,一般适用于连接数较多且连接时 间较长的应用
-
目前 AIO 还没有广泛应用,Netty 也是基于NIO, 而不是AIO, 因此我们就不详解 AIO了,有兴趣的同学可以参考 Java新一代网络编程模型AIO原理及Linux系统 AIO介绍>
http://www.52im.net/thread-306-1-1.html
BIO、NIO、AIO对比表
举例说明
-
同步阻塞:到理发店理发,就一直等理发师,直到轮到自己理发。
-
同步非阻塞:到理发店理发,发现前面有其它人理发,给理发师说 下,先干其他事情,一会过来看是否轮到自己.
-
异步非阻塞:给理发师打电话,让理发师上门服务,自己干其它事 情,理发师自己来家给你理发