线程模型基本介绍
不同的线程模式,对程序的性能有很大影响,为了搞清 Netty 线程模式,我们来系统的讲解下 各个线程模式, 最后看看 Netty 线程模型有什么优越性.
目前存在的线程模型有:
- 传统阻塞 I/O 服务模型
- Reactor 模式
根据 Reactor 的数量和处理资源池线程的数量不同,有 3 种典型的实现
- 单 Reactor 单线程
- 单 Reactor 多线程
- 主从 Reactor 多线程
Netty 线程模式(Netty 主要基于主从 Reactor 多线程模型做了一定的改进,其中主从 Reactor 多线程模型有多 个 Reactor)
传统阻塞 I/O 服务模型
工作原理图
- 黄色的框表示对象
- 蓝色的框表示线程
- 白色的框表示方法(API)
模型特点
- 采用阻塞 IO 模式获取输入的数据
- 每个连接都需要独立的线程完成数据的输入,业务处理, 数据返回
问题分析
- 当并发数很大,就会创建大量的线程,占用很大系统资源
- 连接创建后,如果当前线程暂时没有数据可读,该线程会阻塞在 read 操作,造成线程资源浪费
Reactor 模式
针对传统阻塞 I/O 服务模型的 2 个缺点,解决方案
-
基于 I/O 复用模型:多个连接共用一个阻塞对象,应用程序只需要在一个阻塞对象等待,无需阻塞等待所有连 接。当某个连接有新的数据可以处理时,操作系统通知应用程序,线程从阻塞状态返回,开始进行业务处理 Reactor 对应的叫法: 1. 反应器模式 2. 分发者模式(Dispatcher) 3. 通知者模式(notifier)
-
基于线程池复用线程资源:不必再为每个连接创建线程,将连接完成后的业务处理任务分配给线程进行处理, 一个线程可以处理多个连接的业务
I/O 复用结合线程池,就是 Reactor 模式基本设计思想
-
Reactor 模式,通过一个或多个输入同时传递给服务处理器的模式(基于事件驱动)
-
服务器端程序处理传入的多个请求,并将它们同步分派到相应的处理线程, 因此 Reactor 模式也叫 Dispatcher模式
-
Reactor 模式使用 IO 复用监听事件, 收到事件后,分发给某个线程(进程), 这点就是网络服务器高并发处理关键
Reactor 模式中 核心组成
-
Reactor:Reactor 在一个单独的线程中运行,负责监听和分发事件,分发给适当的处理程序来对 IO 事件做出反应。 它就像公司的电话接线员,它接听来自客户的电话并将线路转移到适当的联系人
-
Handlers:处理程序执行 I/O 事件要完成的实际事件,类似于客户想要与之交谈的公司中的实际官员。Reactor 通过调度适当的处理程序来响应 I/O 事件,处理程序执行非阻塞操作。
Reactor 模式分类
根据 Reactor 的数量和处理资源池线程的数量不同,有 3 种典型的实现
- 单 Reactor 单线程
- 单 Reactor 多线程
- 主从 Reactor 多线程
单 Reactor 单线程
介绍
- Select 是前面 I/O 复用模型介绍的标准网络编程 API,可以实现应用程序通过一个阻塞对象监听多路连接请求
- Reactor 对象通过 Select 监控客户端请求事件,收到事件后通过 Dispatch 进行分发
- 如果是建立连接请求事件,则由 Acceptor 通过 Accept 处理连接请求,然后创建一个 Handler 对象处理连接 完成后的后续业务处理
- 如果不是建立连接事件,则 Reactor 会分发调用连接对应的 Handler 来响应
- Handler 会完成 Read→业务处理→Send 的完整业务流程
结合实例:服务器端用一个线程通过多路复用搞定所有的 IO 操作(包括连接,读、写等),编码简单,清晰明了, 但是如果客户端连接数量较多,将无法支撑,前面的 NIO 案例就属于这种模型。
方案优缺点分析
-
优点:模型简单,没有多线程、进程通信、竞争的问题,全部都在一个线程中完成
-
缺点:
-
性能问题,只有一个线程,无法完全发挥多核 CPU 的性能。Handler 在处理某个连接上的业务时,整个进程无法处理其他连接事件,很容易导致性能瓶颈
-
可靠性问题,线程意外终止,或者进入死循环,会导致整个系统通信模块不可用,不能接收和处理外部消息,造成节点故障
-
-
使用场景:客户端的数量有限,业务处理非常快速,比如 Redis 在业务处理的时间复杂度 O(1) 的情况
案例
服务端
public class Server {
public static void main(String[] args) throws IOException {
//1.获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
//2.切换成非阻塞模式
ssChannel.configureBlocking(false);
//3.绑定连接
ssChannel.bind(new InetSocketAddress(9898));
//4.获取一个选择器
Selector selector = Selector.open();
//5.将通道注册到选择器上,并且指定监听事件(这里是接受事件)
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
Handler handler=new Handler();
//6.轮询式的获取选择器上已经”准备就绪“的事件
while(selector.select()>0){
//7.获取当前选择器中所有注册的“选择键(已就绪的监听事件)”
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
//8.获取准备就绪的事件
SelectionKey sk = it.next();
//9.判断具体是什么事件准备就绪
if(sk.isAcceptable()){
//10.若接受就绪,获取客户端连接
SocketChannel sChannel = ssChannel.accept();
//11.切换到非阻塞模式
sChannel.configureBlocking(false);
//12.将通道注册到选择器上
sChannel.register(selector, SelectionKey.OP_READ);
System.out.println(sChannel.getRemoteAddress()+" 上线...");
}else if(sk.isReadable()){
handler.readData(sk,selector);
}
//15. 取消选择键
it.remove();
}
}
}
}
class Handler{
public void readData(SelectionKey sk,Selector selector) throws IOException {
SocketChannel sChannel=null;
try {
//13.获取当前选择器上“读就绪”状态的通道
sChannel =(SocketChannel) sk.channel();
//14.读取数据
ByteBuffer buffer=ByteBuffer.allocate(1024);
int count=sChannel.read(buffer);
if(count>0){
String msg = new String(buffer.array());
System.out.println("form 客户端: " + msg.trim());
//向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
sendInfoToOtherClients(msg, sChannel,selector);
}
} catch (IOException e) {
try {
System.out.println(sChannel.getRemoteAddress() + " 离线了..");
//取消注册
sk.cancel();
//关闭通道
sChannel.close();
}catch (IOException e2) {
e2.printStackTrace();;
}
}finally {
}
}
public void sendInfoToOtherClients(String msg,SocketChannel self,Selector selector) throws IOException {
//遍历 所有注册到 selector 上的 SocketChannel,并排除 self
for (SelectionKey selectedKey : selector.keys()) {
Channel targetChannel = selectedKey.channel();
if(targetChannel instanceof SocketChannel&&targetChannel!=self){
SocketChannel dest=(SocketChannel)targetChannel;
ByteBuffer buffer=ByteBuffer.wrap(msg.getBytes());
dest.write(buffer);
System.out.println("发送数据");
}
}
}
}
客户端
public class Client {
private static Selector selector;
public static void main(String[] args) throws IOException {
//1.获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
//2.切换成非阻塞模式
sChannel.configureBlocking(false);
//3.分配指定大小的缓冲区
ByteBuffer buffer=ByteBuffer.allocate(1024);
selector=Selector.open();
sChannel.register(selector, SelectionKey.OP_READ);
//4.发送数据给服务端
// buffer.put(new Date().toString().getBytes());
// buffer.flip();
// sChannel.write(buffer);
new Thread() {
public void run() {
while (true) {
try {
readInfo();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.currentThread().sleep(3000);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext()){
String str=scanner.next();
buffer.put((new Date().toString()+"\t"+str).getBytes());
buffer.flip();
sChannel.write(buffer);
buffer.clear();
}
//5.关闭通道
sChannel.close();
}
private static void readInfo() throws IOException{
while (selector.select()>0){
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey sk = it.next();
if(sk.isReadable()){
SocketChannel socketChannel=(SocketChannel) sk.channel();
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
socketChannel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()).trim());
}
}
it.remove();
}
}
}
运行
单 Reactor 多线程
介绍
- Reactor 对象通过 select 监控客户端请求 事件, 收到事件后,通过 dispatch 进行分发
- 如果建立连接请求, 则右 Acceptor 通过 accept 处理连接请求, 然后创建一个 Handler 对象处理完成连接后的各种事件
- 如果不是连接请求,则由 reactor 分发调用连接对应的 handler 来处理
- handler 只负责响应事件,不做具体的业务处理, 通过 read 读取数据后,会分发给后面的 worker 线程池的某个 线程处理业务
- worker 线程池会分配独立线程完成真正的业务,并将结果返回给 handler
- handler 收到响应后,通过 send 将结果返回给 client
方案优缺点分析
-
优点:可以充分的利用多核 cpu 的处理能力
-
缺点:多线程数据共享和访问比较复杂, reactor 处理所有的事件的监听和响应,在单线程运行, 在高并发场
景容易出现性能瓶颈
主从 Reactor 多线程
介绍
针对单 Reactor 多线程模型中,Reactor 在单线程中运行,高并发场景下容易成为性能瓶颈,可以让 Reactor 在 多线程中运行
- Reactor 主线程 MainReactor 对象通过 select 监听连接事件, 收到事件后,通过 Acceptor 处理连接事件
- 当 Acceptor 处理连接事件后,MainReactor 将连接分配给 SubReactor
- subreactor 将连接加入到连接队列进行监听,并创建 handler 进行各种事件处理
- 当有新事件发生时, subreactor 就会调用对应的 handler 处理
- handler 收到响应后,通过 send 将结果返回给 client
- handler 通过 read 读取数据,分发给后面的 worker 线程处理
- worker 线程池分配独立的 worker 线程进行业务处理,并返回结果
- handler 收到响应的结果后,再通过 send 将结果返回给 client
- Reactor 主线程可以对应多个 Reactor 子线程, 即 MainRecator 可以关联多个 SubReactor
结合实例:这种模型在许多项目中广泛使用,包括 Nginx 主从 Reactor 多进程模型,Memcached 主从多线程,Netty 主从多线程模型的支持
方案优缺点分析
- 优点:
- 父线程与子线程的数据交互简单职责明确,父线程只需要接收新连接,子线程完成后续的业务处理。
- 父线程与子线程的数据交互简单,Reactor 主线程只需要把新连接传给子线程,子线程无需返回数据。
- 缺点:编程复杂度较高
Scalable IO in Java 对 Multiple Reactors 的原理图解
Reactor 模式小结
3种模式用生活案例来理解
- 单 Reactor 单线程,前台接待员和服务员是同一个人,全程为顾客服
- 单 Reactor 多线程,1 个前台接待员,多个服务员,接待员只负责接待
- 主从 Reactor 多线程,多个前台接待员,多个服务生
Reactor 模式具有如下的优点
- 响应快,不必为单个同步时间所阻塞,虽然 Reactor 本身依然是同步的
- 可以最大程度的避免复杂的多线程及同步问题,并且避免了多线程/进程的切换开销
- 扩展性好,可以方便的通过增加 Reactor 实例个数来充分利用 CPU 资源
- 复用性好,Reactor 模型本身与具体事件处理逻辑无关,具有很高的复用性
Netty 模型
工作原理示意图-简单版
-
BossGroup 线程维护 Selector , 只关注 Accecpt
-
当接收到 Accept 事件,获取到对应的 SocketChannel, 封装成 NIOScoketChannel 并注册到 Worker 线程(事件循 环), 并进行维护
-
当 Worker 线程监听到 selector 中通道发生自己感兴趣的事件后,就进行处理(就由 handler), 注意 handler 已 经加入到通道
工作原理示意图-进阶版
工作原理示意图-详细版
-
Netty 抽象出两组线程池 BossGroup 专门负责接收客户端的连接, WorkerGroup 专门负责网络的读写
-
BossGroup 和 WorkerGroup 类型都是
NioEventLoopGroup
-
NioEventLoopGroup 相当于一个事件循环组, 这个组中含有多个事件循环 ,即可以有多个线程,每一个事件循环是 NioEventLoop
-
NioEventLoop 表示一个不断循环的执行处理任务的线程, 每个 NioEventLoop 都有一个 selector , 用于监听绑 定在其上的 socket 的网络通讯
-
每个 Boss NioEventLoop 循环执行的步骤有 3 步
- 轮询 accept 事件
- 处理 accept 事件 , 与 client 建立连接 , 生成 NioScocketChannel , 并将其注册到某个 worker NIOEventLoop 上 的 select
- 处理任务队列的任务 , 即 runAllTasks
-
每个 Worker NIOEventLoop 循环执行的步骤
- 轮询 read, write 事件
- 处理 i/o 事件, 即 read , write 事件,在对应 NioScocketChannel 处理
- 处理任务队列的任务 , 即 runAllTasks
-
每个Worker NIOEventLoop 处理业务时,会使用pipeline(管道), pipeline 中包含了 channel , 即通过pipeline可以获取到对应通道, 管道中维护了很多的 处理器
说明
- Netty 抽象出两组线程池,BossGroup 专门负责接收客户端连接,WorkerGroup 专门负责网络读写操作
- NioEventLoop 表示一个不断循环执行处理任务的线程,每个 NioEventLoop 都有一个 selector,用于监听绑定 在其上的 socket 网络通道
- NioEventLoop 内部采用串行化设计,
从消息的读取->解码->处理->编码->发送
,始终由 IO 线程 NioEventLoop 负责 - NioEventLoopGroup 下包含多个 NioEventLoop
- 每个 NioEventLoop 中包含有一个 Selector,一个 taskQueue
- 每个 NioEventLoop 的 Selector 上可以注册监听多个 NioChannel
- 每个 NioChannel 只会绑定在唯一的 NioEventLoop 上
- 每个 NioChannel 都绑定有一个自己的 ChannelPipeline
Netty 快速入门实例-TCP 服务
server
public class Server {
public static void main(String[] args) throws IOException {
//创建BossGroup和WorkerGroup
EventLoopGroup bossGroup=new NioEventLoopGroup();
EventLoopGroup workerGroup=new NioEventLoopGroup();
//创建服务器端的启动对象,配置参数
ServerBootstrap bootstrap=new ServerBootstrap();
try {
//使用链式编程来进行设置
bootstrap.group(bossGroup,workerGroup) //设置两个线程
.channel(NioServerSocketChannel.class) //使用NioServerSocketChannel,作为服务器的通道实现
.option(ChannelOption.SO_BACKLOG,128) //设置线程队列里连接个数
.childOption(ChannelOption.SO_KEEPALIVE,true) //设置保持连接状态
.childHandler(new ChannelInitializer<SocketChannel>() {
//给pipeline设置处理器
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ServerHandler());
}
}); //给我们的workerGroup的EventLoop对应的管道设置处理器
System.out.println("服务器 is ready ...");
//绑定一个端口并且同步,生成一个ChannelFuture对象
ChannelFuture cf = bootstrap.bind(6668).sync();
//对关闭通道进行监听
cf.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
serverHandler
public class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* @Description 读取数据事件(这里我们可以读取客户端发送的消息)
* @date 2020/7/23 10:33
* @param ctx 上下文对象,含有:管道(pipeline),通道(channel),地址
* @param msg 客户端发送的数据
* @return void
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// System.out.println("服务器读取线程"+Thread.currentThread().getName());
// System.out.println("server ctx = "+ctx);
// System.out.println("看看channel和pipeline的关系");
// Channel channel = ctx.channel();
// ChannelPipeline pipeline = ctx.pipeline();//本质是一个双向链表
//
// //将msg转为一个ByteBuf
// //ByteBuf是Netty提供的,不是NIO的ByteBuffer
// ByteBuf buf=(ByteBuf) msg;
// System.out.println("客户端发送消息:"+buf.toString(CharsetUtil.UTF_8));
// System.out.println("客户端地址:"+ctx.channel().remoteAddress());
//比如我们有一个非常耗时的业务->异步执行->提交该channel对应的NioEventLoop的taskQueue中
// Thread.sleep(10000);
// ctx.writeAndFlush(Unpooled.copiedBuffer("hello 客户端",CharsetUtil.UTF_8));
// System.out.println("go on ...");
//解决方案1 用户程序自定义的普通任务
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1*1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(new Date().toString()+":"+"hello 客户端1",CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1*1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(new Date().toString()+":"+"hello 客户端2",CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//解决方案二 用户自定义定时任务
ctx.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5*1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(new Date().toString()+":"+"hello 客户端3",CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},5, TimeUnit.SECONDS);
System.out.println("go on ...");
}
}
/**
* @Description 数据读取完毕
* @date 2020/7/23 10:46
* @param ctx
* @return void
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将数据写入到缓冲并刷新
//一般来讲,我们队发送的数据进行编码
ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端",CharsetUtil.UTF_8));
}
/**
* @Description 处理异常,一般是需要管理通道
* @date 2020/7/23 11:13
* @param ctx
* @param cause
* @return void
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.channel().close();
}
}
client
public class Client {
public static void main(String[] args) {
//客户端需要一个事件循环组
EventLoopGroup eventExecutors=new NioEventLoopGroup();
try {
//创建客户端启动对象
Bootstrap bootstrap=new Bootstrap();
//设置相关参数
bootstrap.group(eventExecutors) //设置线程组
.channel(NioSocketChannel.class) //设置客户端通道的实现类(反射)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientHandler()); //加入自己的处理器
}
});
System.out.println("客户端 ok...");
//启动客户端去连接服务器端
//关于ChannelFuture要分析,涉及到netty的异步模型
ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("127.0.0.1", 6668)).sync();
//关闭通道进行监听
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
eventExecutors.shutdownGracefully();
}
}
}
clientHandler
public class ClientHandler extends ChannelInboundHandlerAdapter {
/**
* @Description 当通道就绪时会触发该方法
* @date 2020/7/23 11:27
* @param ctx
* @return void
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client"+ctx);
ctx.writeAndFlush(Unpooled.copiedBuffer("hello,server", CharsetUtil.UTF_8));
}
/**
* @Description 当通道有读取事件时,会触发
* @date 2020/7/23 11:29
* @param ctx
* @param msg
* @return void
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf=(ByteBuf)msg;
System.out.println("服务器回复的消息:"+((ByteBuf) msg).toString(CharsetUtil.UTF_8));
System.out.println("服务器的地址:"+ctx.channel().remoteAddress());
}
}
源码分析
bossGroup和workerGroup含有的子线程的个数(默认的NioEventLoop个数),默认为cpu核数 * 2
当启动9个客户端时,看下线程的分配情况
服务器 is ready ...
服务器读取线程nioEventLoopGroup-3-1
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x45510c71, L:/127.0.0.1:6668 - R:/127.0.0.1:62038])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62038
服务器读取线程nioEventLoopGroup-3-2
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x29926adb, L:/127.0.0.1:6668 - R:/127.0.0.1:62073])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62073
服务器读取线程nioEventLoopGroup-3-3
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x60a3c1f1, L:/127.0.0.1:6668 - R:/127.0.0.1:62129])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62129
服务器读取线程nioEventLoopGroup-3-4
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x2e2d621c, L:/127.0.0.1:6668 - R:/127.0.0.1:62154])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62154
服务器读取线程nioEventLoopGroup-3-5
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x172a53cc, L:/127.0.0.1:6668 - R:/127.0.0.1:62182])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62182
服务器读取线程nioEventLoopGroup-3-6
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x4cd7905b, L:/127.0.0.1:6668 - R:/127.0.0.1:62209])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62209
服务器读取线程nioEventLoopGroup-3-7
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x1cb0454b, L:/127.0.0.1:6668 - R:/127.0.0.1:62234])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62234
服务器读取线程nioEventLoopGroup-3-8
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x87c91e13, L:/127.0.0.1:6668 - R:/127.0.0.1:62261])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62261
服务器读取线程nioEventLoopGroup-3-1
server ctx = ChannelHandlerContext(ServerHandler#0, [id: 0x8709b039, L:/127.0.0.1:6668 - R:/127.0.0.1:62286])
客户端发送消息:hello,server
客户端地址:/127.0.0.1:62286
可以看到确实是采取轮流分配的方式来分配线程的
我们可以自行设置
EventLoopGroup bossGroup=new NioEventLoopGroup(1);
EventLoopGroup workerGroup=new NioEventLoopGroup();
此时再看
任务队列中的 Task 有 3 种典型使用场景
-
用户程序自定义的普通任务
-
用户自定义定时任务
-
非当前 Reactor 线程调用 Channel 的各种方法
例如在推送系统的业务线程里面,根据用户的标识,找到对应的 Channel 引用,然后调用 Write 类方法向该用户推送消息,就会进入到这种场景。最终的 Write 会提交到任务队列中后被异步消费
Thread.sleep(10000);
ctx.writeAndFlush(Unpooled.copiedBuffer("hello 客户端",CharsetUtil.UTF_8));
System.out.println("go on ...");
此时会一致阻塞在这里
用户程序自定义的普通任务
//解决方案1 用户程序自定义的普通任务
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10*1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(new Date().toString()+":"+"hello 客户端1",CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(20*1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(new Date().toString()+":"+"hello 客户端2",CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("go on ...");
此时任务队列中有两个任务(注意这两个任务事由一个线程来处理的),第二个任务的运行时间是10+20秒
运行
客户端 ok...
clientChannelHandlerContext(ClientHandler#0, [id: 0x7028b530, L:/127.0.0.1:50197 - R:/127.0.0.1:6668])
服务器回复的消息:Thu Jul 23 15:16:08 CST 2020:hello,客户端
服务器的地址:/127.0.0.1:6668
服务器回复的消息:Thu Jul 23 15:16:18 CST 2020:hello 客户端1
服务器的地址:/127.0.0.1:6668
服务器回复的消息:Thu Jul 23 15:16:38 CST 2020:hello 客户端2
服务器的地址:/127.0.0.1:6668
用户自定义定时任务
//解决方案二 用户自定义定时任务
ctx.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5*1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(new Date().toString()+":"+"hello 客户端3",CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},5, TimeUnit.SECONDS);
运行
客户端 ok...
clientChannelHandlerContext(ClientHandler#0, [id: 0xb33aedd3, L:/127.0.0.1:50405 - R:/127.0.0.1:6668])
服务器回复的消息:Thu Jul 23 15:25:05 CST 2020:hello,客户端
服务器的地址:/127.0.0.1:6668
服务器回复的消息:Thu Jul 23 15:25:06 CST 2020:hello 客户端1
服务器的地址:/127.0.0.1:6668
服务器回复的消息:Thu Jul 23 15:25:07 CST 2020:hello 客户端2
服务器的地址:/127.0.0.1:6668
服务器回复的消息:Thu Jul 23 15:25:15 CST 2020:hello 客户端3
服务器的地址:/127.0.0.1:6668
可以看到,定时任务和普通任务是区分开的
非当前 Reactor 线程调用 Channel 的各种方法
我们可以在初始化处理器的时候,将channel放到一个集合中,然后再handler中可以处理相关业务。
异步模型
介绍
- 异步的概念和同步相对。当一个异步过程调用发出后,调用者不能立刻得到结果。实际处理这个调用的组件在 完成后,通过状态、通知和回调来通知调用者
- Netty 中的 I/O 操作是异步的,包括 Bind、Write、Connect 等操作会简单的
返回一个 ChannelFuture
。 - 调用者并不能立刻获得结果,而是通过 Future-Listener 机制,用户可以方便的主动获取或者通过通知机制获得 IO 操作结果
- Netty 的异步模型是建立在 future 和 callback 的之上的。callback 就是回调。重点说 Future,它的核心思想 是:假设一个方法 fun,计算过程可能非常耗时,等待 fun 返回显然不合适。那么可以在调用 fun 的时候,立 马返回一个Future,后续可以通过 Future 去监控方法 fun 的处理过程(即 : Future-Listener 机制)
Future 说明
- 表示异步的执行结果, 可以通过它提供的方法来检测执行是否完成,比如检索计算等等
- ChannelFuture 是一个接口 : public interface ChannelFuture extends Future 我们可以添加监听器,当监听的事件发生时,就会通知到监听器
工作原理示意图
-
在使用 Netty 进行编程时,拦截操作和转换出入站数据只需要您提供 callback 或利用 future 即可。这使得链 式操作简单、高效, 并有利于编写可重用的、通用的代码。
-
Netty 框架的目标就是让你的业务逻辑从网络基础应用编码中分离出来、解脱出来
Future-Listener 机制
- 当 Future 对象刚刚创建时,处于非完成状态,调用者可以通过返回的 ChannelFuture 来获取操作执行的状态, 注册监听函数来执行完成后的操作。
- 常见有如下操作
- 通过 isDone 方法来判断当前操作是否完成
- 通过 isSuccess 方法来判断已完成的当前操作是否成功
- 通过 getCause 方法来获取已完成的当前操作失败的原因
- 通过 isCancelled 方法来判断已完成的当前操作是否被取消
- 通过 addListener 方法来注册监听器,当操作已完成(isDone 方法返回完成),将会通知指定的监听器;如果Future 对象已完成,则通知指定的监听器
例子
//绑定一个端口并且同步,生成一个ChannelFuture对象
ChannelFuture cf = bootstrap.bind(6668).sync();
//给 cf 注册监听器,监控我们关心的事件
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if(future.isSuccess()){
System.out.println("监听端口成功");
}else{
System.out.println("监听端口失败");
}
}
});
运行
服务器 is ready ...
监听端口成功
快速入门实例-HTTP 服务
目的:Netty 可以做 Http 服务开发,并且理解 Handler 实例和客户端及其请求的关系
server
public class Server {
public static void main(String[] args) {
EventLoopGroup bossGroup=new NioEventLoopGroup(1);
EventLoopGroup workGroup=new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap=new ServerBootstrap();
serverBootstrap.group(bossGroup,workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.childHandler(new ServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(40000)).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
initializer
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//向管道加入处理器
//得到管道
ChannelPipeline pipeline = ch.pipeline();
//加入一个netty提供的httpServerCodec
//netty提供的处理http的编码解码器
pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
//增加一个自定义handler
pipeline.addLast("HttpServerHandler",new HttpServerHandler());
}
}
serverHadndler
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
/**
* @Description 读取客户端的数据
* @date 2020/7/23 17:21
* @param ctx
* @param msg
* @return void
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
//判断msg是不是httpRequest请求
if(msg instanceof HttpRequest){
System.out.println("msg类型:"+msg.getClass());
System.out.println("客户端地址:"+ctx.channel().remoteAddress());
System.out.println("pipeline:"+ctx.pipeline().hashCode()+" channel:"+ctx.channel().hashCode());
//获取到
HttpRequest httpRequest=(HttpRequest) msg;
//获取uri
URI uri = new URI(httpRequest.uri());
if("/favicon.ico".equals(uri.getPath())){
System.out.println("请求了 /favicon.ico ,不做响应");
return;
}
//回复信息给浏览器
ByteBuf buf= Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);
//构造相应的http的相应,即httpresponse
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,buf.readableBytes());
//将构建好的response返回
ctx.writeAndFlush(response);
}
}
}
后台输出
msg类型:class io.netty.handler.codec.http.DefaultHttpRequest
客户端地址:/0:0:0:0:0:0:0:1:54190
pipeline:1483512378 channel:1336530724
msg类型:class io.netty.handler.codec.http.DefaultHttpRequest
客户端地址:/0:0:0:0:0:0:0:1:54190
pipeline:1483512378 channel:1336530724
请求了 /favicon.ico ,不做响应
msg类型:class io.netty.handler.codec.http.DefaultHttpRequest
客户端地址:/0:0:0:0:0:0:0:1:54194
pipeline:1928055277 channel:-2011214508
msg类型:class io.netty.handler.codec.http.DefaultHttpRequest
客户端地址:/0:0:0:0:0:0:0:1:54194
pipeline:1928055277 channel:-2011214508
请求了 /favicon.ico ,不做响应
因为http是短连接,每次访问的时候会创建新的pipeline和channel