前面給大家介紹了NIO,我們會發現用NIO實作異步非阻塞的網絡通信代碼量非常大,而且并不是很好了解,在實際的開發中一般我們也都是會實作基于NIO的架構來操作的,比如Netty,這樣開發效率有高而且Bug也少。
Netty入門案例
官網:https://netty.io/
環境準備
你可以去官網下載下傳對應的jar包依賴,然後建立普通的java項目即可,也可以跟着我通過建立maven項目來實作,如下是會用到的依賴
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
log4j.properties屬性檔案
log4j.rootCategory=info, stdout , R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=C:\\Tomcat 5.5\\logs\\qc.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n
服務端
TimerServer
package com.dpb.netty.demo;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class TimerServer {
public void bind(int port) throws Exception{
// 配置服務端的NIO線程組
// 服務端接受用戶端的連接配接
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
// 進行SocketChannel的網絡讀寫
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
// 用于啟動NIO服務端的輔助啟動類,目的是降低服務端的開發複雜度
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
// 設定Channel
.channel(NioServerSocketChannel.class)
// 設定TCP參數
.option(ChannelOption.SO_BACKLOG, 1024)
// 綁定I/O事件的處理類ChildChannelHandler
.childHandler(new ChildChannelHandler());
// 綁定端口,同步等待成功
ChannelFuture f = b.bind(port).sync();
// 等待服務端監聽端口關閉
f.channel().closeFuture().sync();
} finally {
// 優雅退出,釋放線程池資源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new TimerServerHandler());
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
new TimerServer().bind(port);
}
}
TimerServerHandler
package com.dpb.netty.demo;
import java.nio.ByteBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* 用于對網絡事件進行讀寫操作
* @author 波波烤鴨
* @email [email protected]
*
*/
public class TimerServerHandler extends ChannelHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// ByteBuf 類似于NIO中的java.nio.ByteBuffer對象,
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req,"utf-8");
System.out.println("The time server receive order : "+body);
String currentTime = "Query time order".equalsIgnoreCase(body)?new java.util.Date(System.currentTimeMillis()).toString():"BAD ORDER";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
ctx.close();
}
}
用戶端
TimeClient
package com.dpb.netty.demo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class TimeClient {
public static void main(String[] args) throws Exception {
int port = 8080;
new TimeClient().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>() {
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new TimeClientHandler());
}
});
// 發起異步連接配接操作
ChannelFuture f = b.connect(host,port).sync();
// 等待用戶端鍊路關閉
f.channel().closeFuture().sync();
}catch(Exception e){
e.printStackTrace();
}finally{
// 優雅退出,釋放NIO線程組
group.shutdownGracefully();
}
}
}
TimeClientHandler
package com.dpb.netty.demo;
import java.util.logging.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class TimeClientHandler extends ChannelHandlerAdapter{
private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
private final ByteBuf firstMessage;
public TimeClientHandler(){
byte[] req = "Query time order".getBytes();
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(firstMessage);
}
@Override
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("Now is :"+body);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
logger.warning("Unexpected exception from downstream:"+cause.getMessage());
ctx.close();
}
}

測試
先啟動伺服器,再啟動用戶端,輸出如下:
The time server receive order : Query time order
Now is :Thu Apr 11 22:22:58 CST 2019
總結
通過案例使用Netty實作了用戶端和伺服器的通信,可以發現相比傳統的NIO程式,Netty的代碼更加簡潔,開發難度更低,擴充性也更好,非常适合作為基礎通信架構被使用者內建和使用