前面學習了用Java原生NIO的編程實踐,過程還是挺複雜的,需要熟練掌握Selector,ServerSocketChannel握,SocketChannel,ByteBuffer等。所以在絕大多數業務場景中我們可以使用Netty來進行NIO編程。先總結一下Netty的優點:
- API使用簡單,開發門檻低
- 功能強大,預製了多種編解碼功能,支持多種主流協議
- 定製能力強,可以通過ChannelHandler對通信框架進行靈活的擴展
- 性能高,成熟,穩定,社區活躍,版本迭代週期短
- 經歷了大規模的商業應用考驗,質量得到驗證等
至於安裝就不多說了,只要下載他的JAR包然後在普通java項目中導入就可以了。
編程實戰
可以對比一下之前的原生NIO代碼,是簡潔了許多。
Netty服務端
package com.ph.Netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Create by PH on 2018/11/3
*/
public class NettyServer {
public static void main(String[] args) throws Exception {
int port = 8080;
if(args !=null && args.length>0) {
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e) {
//採用默認值
}
}
new NettyServer().bind(port);
}
public void bind(int port) throws Exception{
//NioEventLoopGroup是一個線程組,包含了一組NIO線程,專門用於網絡事件的處理,
//實際上他們就是Reactor線程組
//bossGroup僅接收客戶端連接,不做複雜的邏輯處理,爲了儘可能減少資源的佔用,取值越小越好
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
//用於進行SocketChannel的網絡讀寫
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//是Netty用於啓動NIO服務端的輔助啓動類,目的是降低服務端的開發複雜度
ServerBootstrap b = new ServerBootstrap();
//配置NIO服務端
b.group(bossGroup, workerGroup)
//指定使用NioServerSocketChannel產生一個Channel用來接收連接,他的功能對應於JDK
// NIO類庫中的ServerSocketChannel類。
.channel(NioServerSocketChannel.class)
//BACKLOG用於構造服務端套接字ServerSocket對象,標識當服務器請求處理線程全滿時,
// 用於臨時存放已完成三次握手的請求的隊列的最大長度。如果未設置或所設置的值小於1,
// Java將使用默認值50。
.option(ChannelOption.SO_BACKLOG, 1024)
//綁定I/O事件處理類,作用類似於Reactor模式中的Handler類,主要用於處理網絡I/O事件
.childHandler(new ChildChannelHandler());
//綁定端口,同步等待綁定操作完成,完成後返回一個ChannelFuture,用於異步操作的通知回調
ChannelFuture f = b.bind(port).sync();
//等待服務端監聽端口關閉之後才退出main函數
f.channel().closeFuture().sync();
} finally {
//退出,釋放線程池資源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new ServerHandler());
}
}
}
/**
* ChannelInboundHandlerAdapter實現自ChannelInboundHandler
* ChannelInboundHandler提供了不同的事件處理方法可通過重寫來自定義處理方式
*/
class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* 接受客戶端發送的消息
* @param ctx
* @param msg
* @throws Exception
*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//類似JDK中的ByteBuffer對象,不過它提供了更加強大和靈活的功能
ByteBuf buf = (ByteBuf) msg;
//通過readableBytes()方法獲取緩衝區可讀的字節數
byte[] req = new byte[buf.readableBytes()];
//將緩衝區中的字節數組複製到新建的byte數組中
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("Server receive: " + body);
//獲得ByteBuf類型的數據
ByteBuf resp = Unpooled.copiedBuffer("Server message".getBytes());
//向客戶端發送消息,不直接將消息寫入SocketChannel中,只是把待發送的消息放到發送緩存數組中,
//再通過調用flush方法將緩衝區中的消息全部寫到SocketChannel中
ctx.write(resp);
}
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//將消息發送隊列中的消息寫入到SocketChannel中發送給對方
ctx.flush();
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//當發生異常時釋放資源
ctx.close();
}
}
Netty客戶端
package com.ph.Netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* Create by PH on 2018/11/3
*/
public class NettyClient {
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
//採用默認值
}
}
new NettyClient().connect(port, "127.0.0.1");
}
public void connect(int port, String host) throws Exception{
//配置客戶端NIO線程組
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) throws Exception{
ch.pipeline().addLast(new ClientHandler());
}
});
//發起異步連接操作
ChannelFuture f = b.connect(host, port).sync();
//等待客戶端鏈路關閉
f.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}
class ClientHandler extends ChannelInboundHandlerAdapter {
private final ByteBuf msg;
public ClientHandler() {
byte[] req = "Client message".getBytes();
msg = Unpooled.buffer(req.length);
msg.writeBytes(req);
}
/**
* 當客戶端和服務端TCP鏈路建立成功之後,Netty的NIO線程會調用此方法
* @param ctx
*/
public void channelActive(ChannelHandlerContext ctx) {
//發送消息到服務端
ctx.writeAndFlush(msg);
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "utf-8");
System.out.println("Client receive :" + body);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}