深入瞭解Netty【六】Netty工作原理
阿新 • • 發佈:2020-06-24
引言
前面學習了NIO與零拷貝、IO多路複用模型、Reactor主從模型。 伺服器基於IO模型管理連線,獲取輸入資料,又基於執行緒模型,處理請求。 下面來學習Netty的具體應用。
1、Netty執行緒模型
Netty執行緒模型是建立在Reactor主從模式的基礎上,主從 Rreactor 多執行緒模型:
但是在Netty中,bossGroup相當於mainReactor,workerGroup相當於SubReactor與Worker執行緒池的合體。如:
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap server = new ServerBootstrap();
server.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class);
複製程式碼
- bossGroup bossGroup執行緒池負責監聽埠,獲取一個執行緒作為MainReactor,用於處理埠的Accept事件。
- workerGroup workerGroup執行緒池負責處理Channel(通道)的I/O事件,並處理相應的業務。
在啟動時,可以初始化多個執行緒。
EventLoopGroup bossGroup = new NioEventLoopGroup(2);
EventLoopGroup workerGroup = new NioEventLoopGroup(3);
複製程式碼
2、Netty示例(客戶端、伺服器)
下面的例子演示了Netty的簡單使用。
2.1、服務端
2.1.1、 EchoServerHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
/**
* EchoServerHandler
*/
// 標識這類的例項之間可以在 channel 裡面共享
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx,Object msg) {
ByteBuf in = (ByteBuf) msg;
System.out.println("Server received: " in.toString(CharsetUtil.UTF_8));
ctx.write(in);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
複製程式碼
2.1.2、 EchoServer
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.net.InetSocketAddress;
/**
* Echo服務端
*/
public class EchoServer {
private final int port;
private EchoServer(int port) {
this.port = port;
}
private void start() throws Exception {
//建立 EventLoopGroup
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup work = new NioEventLoopGroup();
try {
//建立 ServerBootstrap
ServerBootstrap b = new ServerBootstrap();
b.group(boss,work)
//指定使用 NIO 的傳輸 Channel
.channel(NioServerSocketChannel.class)
//設定 socket 地址使用所選的埠
.localAddress(new InetSocketAddress(port))
//新增 EchoServerHandler 到 Channel 的 ChannelPipeline
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new EchoServerHandler());
}
});
//繫結的伺服器;sync 等待伺服器關閉
ChannelFuture f = b.bind().sync();
System.out.println(EchoServer.class.getName() " started and listen on " f.channel().localAddress());
//關閉 channel 和 塊,直到它被關閉
f.channel().closeFuture().sync();
} finally {
//關機的 EventLoopGroup,釋放所有資源。
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception {
//設定埠值(丟擲一個 NumberFormatException 如果該埠引數的格式不正確)
int port = 9999;
//伺服器start()
new EchoServer(port).start();
}
}
複製程式碼
2.2、客戶端
2.2.1、EchoClientHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!",CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) {
cause.printStackTrace();
ctx.close();
}
@Override
protected void messageReceived(ChannelHandlerContext ctx,ByteBuf msg) {
System.out.println("Client received: " msg.toString(CharsetUtil.UTF_8));
}
}
複製程式碼
2.2.2、EchoClient
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.net.InetSocketAddress;
public class EchoClient {
private final String host;
private final int port;
private EchoClient(String host,int port) {
this.host = host;
this.port = port;
}
private void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
//建立 Bootstrap
Bootstrap b = new Bootstrap();
//指定 EventLoopGroup 來處理客戶端事件。
//由於使用 NIO 傳輸,所以用到了 NioEventLoopGroup 的實現
b.group(group)
//使用的 channel 型別是一個用於 NIO 傳輸
.channel(NioSocketChannel.class)
//設定伺服器的 InetSocketAddress
.remoteAddress(new InetSocketAddress(host,port))
//當建立一個連線和一個新的通道時,建立新增到 EchoClientHandler 例項 到 channel pipeline
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new EchoClientHandler());
}
});
//連線到遠端;等待連線完成
ChannelFuture f = b.connect().sync();
//阻塞直到 Channel 關閉
f.channel().closeFuture().sync();
} finally {
//呼叫 shutdownGracefully() 來關閉執行緒池和釋放所有資源
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception {
//伺服器地址及埠
String host = "localhost";
int port = 9999;
new EchoClient(host,port).start();
}
}
複製程式碼
3、Netty工作原理
服務端包含了1個boss NioEventLoopGroup和1個work NioEventLoopGroup。 NioEventLoopGroup相當於1個事件迴圈組,組內包含多個事件迴圈(NioEventLoop),每個NioEventLoop包含1個Selector和1個事件迴圈執行緒。
3.1、boss NioEventLoop迴圈任務
- 輪詢Accept事件。
- 處理Accept IO事件,與Client建立連線,生成NioSocketChannel,並將NioSocketChannel註冊到某個work NioEventLoop的Selector上。
- 處理任務佇列中的任務。
3.2、work NioEventLoop迴圈任務
- 輪詢Read、Write事件。
- 處理IO事件,在NioSocketChannel可讀、可寫事件發生時進行處理。
- 處理任務佇列中的任務。
3.3、任務佇列中的任務
- 使用者程式自定義的普通任務
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
//...
}
});
複製程式碼
-
非當前 Reactor 執行緒呼叫 Channel 的各種方法 例如在推送系統的業務執行緒裡面,根據使用者的標識,找到對應的 Channel 引用,然後呼叫 Write 類方法向該使用者推送訊息,就會進入到這種場景。最終的 Write 會提交到任務佇列中後被非同步消費。
-
使用者自定義定時任務
ctx.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
//...
}
},60,TimeUnit.SECONDS);
複製程式碼
參考
這可能是目前最透徹的Netty原理架構解析 Netty 實戰精髓篇 Netty入門教程 Essential Netty in Action