1、Netty模型
1.1、简单原理示意图
![](https://i-blog.csdnimg.cn/blog_migrate/4eecb66bbb5577cc1beecfd3d2060cdf.png)
1.2、示意图解释
![](https://i-blog.csdnimg.cn/blog_migrate/49bda9bd81aea1be7a534823b4886ff1.png)
1.3、原理示意图进阶版
![](https://i-blog.csdnimg.cn/blog_migrate/fba732e034270b21af67209c3de400c3.png)
1.4、原理示意图最终版
![](https://i-blog.csdnimg.cn/blog_migrate/ef16cc9063abfddf5e7d2bed3a4af63b.png)
1.5、示意图解释
![](https://i-blog.csdnimg.cn/blog_migrate/1b934637cf3c71ad3b9076bc954c18c7.png)
![](https://i-blog.csdnimg.cn/blog_migrate/0d4d0819b0442becd672f1f870029b82.png)
2、Netty快速入门案例 - TCP服务
2.1、NettyServer
/**
* @author wzcstart
* @date 2021/6/23 - 23:51
*/
public class NettyServer {
public static void main(String[] args) throws Exception{
//创建BossGroup 和 WorkerGroup
//说明
//1、 创建两个线程组 boosGroup 和workerGroup
//2、 bossGroup 只是处理连接请求,真正的和客户端业务处理,会交给workerGroup完成
//3、 两个都是无限循环
//4、 boosGroup 和 workerGroup 默认有 内核*2 个NioEventLoop
// NettyRuntime.availableProcessors() * 2
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//创建服务端的启动对象,配置参数
ServerBootstrap bootstrap = new ServerBootstrap();
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 ch) throws Exception {
ch.pipeline().addLast(new NettyServerHandler());
}
}); // 给我们的workerGroup 的 EventLoop 对应的管道设置处理器
System.out.println("......服务端 is ready");
//绑定一个端口并同步返回,生成了一个 ChannelFuture 对象
//启动服务器(并绑定端口)
ChannelFuture cf = bootstrap.bind(6668).sync();
//对关闭通道进行监听
cf.channel().closeFuture().sync();
}finally {
//关闭
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
2.2、NettyServerHandler
/**
* @author wzcstart
* @date 2021/6/24 - 22:19
*/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
/**
* 读取数据
* @param ctx 通道处理器上下文,封装了很多对象
* @param msg 客户端发送的消息
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("当前读取的线程:"+Thread.currentThread().getName());
System.out.println("server ctx = "+ctx);
Channel channel = ctx.channel();
ChannelPipeline pipeline = ctx.pipeline();
//将 msg 转换为ByteBuf
//ByteBuf 是netty包下的
ByteBuf buf = (ByteBuf) msg;
System.out.println("服务器发送的消息是:"+buf.toString(CharsetUtil.UTF_8));
System.out.println("客户端地址:"+ channel.remoteAddress());
}
/**
* 读取数据完毕
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//writeAndFlush 是 write + flush
//将数据写入到缓存,并刷新
//一般讲,我们对这个发送的数据进行编码
ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~", CharsetUtil.UTF_8));
}
// 处理异常,一般关闭通道
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
2.3、NettyClient
/**
* @author wzcstart
* @date 2021/6/24 - 22:43
*/
public class NettyClient {
public static void main(String[] args) throws Exception {
//客户端需要一个循环事件组
EventLoopGroup group = new NioEventLoopGroup();
try {
//客户端启动设置
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group) // 指定循环事件组
.channel(NioSocketChannel.class)// 指定通道
.handler(new ChannelInitializer<SocketChannel>() { //添加处理器
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器
}
});
System.out.println("客户端 is ok...");
//启动客户端去连接服务器端
//关于ChannelFuture 要分析,涉及 netty 异步模型
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
//异步监听关闭连接
channelFuture.channel().closeFuture().sync();
} finally {
//关闭
group.shutdownGracefully();
}
}
}
2.4、NettyClientHandler
/**
* @author wzcstart
* @date 2021/6/24 - 22:59
*/
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
//当通道连接成功
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client ctx ="+ctx);
//给服务端发送消息
ctx.writeAndFlush(Unpooled.copiedBuffer("hello,服务端", CharsetUtil.UTF_8));
}
//监听到服务端发送来的消息
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
System.out.println("服务端发送的消息是:"+buf.toString(CharsetUtil.UTF_8));
System.out.println("服务端地址:"+ctx.channel().remoteAddress());
}
//处理异常
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
3、Task三种经典使用场景
3.1、说明
![](https://i-blog.csdnimg.cn/blog_migrate/e8c7591eadd45e392bd5f6b2e2d2ce90.png)
![](https://i-blog.csdnimg.cn/blog_migrate/5994ffb8111b5477b082142f889f1bb4.png)
3.2、代码演示
/**
* 读取数据
* @param ctx 通道处理器上下文,封装了很多对象
* @param msg 客户端发送的消息
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//用户自定义任务 - taskQueue
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"执行任务一");
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
ctx.channel().writeAndFlush(Unpooled.copiedBuffer("任务一",CharsetUtil.UTF_8));
}
});
ctx.channel().eventLoop().execute(()->{
try {
System.out.println(Thread.currentThread().getName()+"执行任务二");
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
ctx.channel().writeAndFlush(Unpooled.copiedBuffer("任务二",CharsetUtil.UTF_8));
});
//用户自定义定时任务 - scheduleTaskQueue
System.out.println("go on ...");
/*System.out.println("当前读取的线程:"+Thread.currentThread().getName());
System.out.println("server ctx = "+ctx);
Channel channel = ctx.channel();
ChannelPipeline pipeline = ctx.pipeline();
//将 msg 转换为ByteBuf
//ByteBuf 是netty包下的
ByteBuf buf = (ByteBuf) msg;
System.out.println("服务器发送的消息是:"+buf.toString(CharsetUtil.UTF_8));
System.out.println("客户端地址:"+ channel.remoteAddress());*/
}
4、代码套路方案再说明
![](https://i-blog.csdnimg.cn/blog_migrate/16645114e79127133666994d5202aec6.png)
5、异步模型
5.1、基本介绍
![](https://i-blog.csdnimg.cn/blog_migrate/14dbdcd9b3e695e6727aa6e48d01003f.png)
5.2、Future说明
![](https://i-blog.csdnimg.cn/blog_migrate/3f5a353f4c02ffba2ebb9e01618b020c.png)
5.3、工作原理示意图
![](https://i-blog.csdnimg.cn/blog_migrate/502a1eff170ebb6f9bf355a36f1a3687.png)
![](https://i-blog.csdnimg.cn/blog_migrate/ffafa01d4b85252156e346419a90d5a1.png)
5.4、Future-Listener
![](https://i-blog.csdnimg.cn/blog_migrate/ca12cecc27d44cbcb6d2ec949235a484.png)
![](https://i-blog.csdnimg.cn/blog_migrate/0b67bfd94722dd35b3ffe5a894307c59.png)
ChannelFuture cf = bootstrap.bind(6668).sync();
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (cf.isSuccess()){
System.out.println("绑定成功");
}else{
System.out.println("绑定失败");
}
}
});
6、Netty核心组件
6.1、Bootstrap、ServerBootstrap - 引导器
![](https://i-blog.csdnimg.cn/blog_migrate/4663d2ba8ea953e607288b1636cd6cff.png)
6.2、Future、ChannelFuture
![](https://i-blog.csdnimg.cn/blog_migrate/74401ae3ca5a72a4c2a94075b524e3e5.png)
6.3、Channel
![](https://i-blog.csdnimg.cn/blog_migrate/f2d4c2af8187a4e0cf59f396caaa1fd2.png)
6.4、Selector
![](https://i-blog.csdnimg.cn/blog_migrate/3c3cbbd65f86a5a5a4da6d5421b09f35.png)
6.5、ChannelHandler及其实现类
![](https://i-blog.csdnimg.cn/blog_migrate/bdc10e6f9946bd0de261c1b08eb727e6.png)
![](https://i-blog.csdnimg.cn/blog_migrate/442b4c3101a9fe2ec9bd15b41d9b447d.png)
public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler {
public ChannelInboundHandlerAdapter() { }
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelRegistered();
}
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelUnregistered();
}
//通道就绪事件
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelActive();
}
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelInactive();
}
//通道读取数据事件
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.fireChannelRead(msg);
}
//数据读取完毕事件
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelReadComplete();
}
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
ctx.fireUserEventTriggered(evt);
}
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelWritabilityChanged();
}
//通道发生异常事件
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.fireExceptionCaught(cause);
}
}
6.6、ChannelPipeline和ChannelPipeline
![](https://i-blog.csdnimg.cn/blog_migrate/649029273c9f473164629bf6f49fe4c6.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f078eb5d063a7aec4c6bd1ef29d8c0fa.png)
6.7、ChannelHandlerContext
![](https://i-blog.csdnimg.cn/blog_migrate/247d181423d41a72ff7c51159819934f.png)
![](https://i-blog.csdnimg.cn/blog_migrate/0d71437df002af63e6db554daba635be.png)
6.8、ChannelOption
![](https://i-blog.csdnimg.cn/blog_migrate/ef035582fe0ca962ffe246a9ff479a9b.png)
6.9、EventLoopGroup和其实现类NioEventLoopGroup
![](https://i-blog.csdnimg.cn/blog_migrate/679e473149d2c709df442b8976e940aa.png)
![](https://i-blog.csdnimg.cn/blog_migrate/9c00ae6509024a8e1b5dd30340db7f61.png)
6.10、Unpooled
![](https://i-blog.csdnimg.cn/blog_migrate/c774322bbe9d0d99ab84dbc174ce9899.png)
6.10.1、案例一
package com.guiguixia.netty.buf;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.util.LinkedList;
/**
* @author wzcstart
* @date 2021/6/27 - 21:51
*/
public class NettyByteBuf01 {
public static void main(String[] args){
//1、 构建一个ByteBuf
//2、 ByteBuf 不用向 ByteBuffer 一样使用 flip()方法反转,
// 因为 ByteBuf 内部维护了 writerIndex 和 readIndex
//3、 ByteBuf 通过 0 -- readIndex -- WriterIndex -- capacity 分成三段
// 0 -- readIndex 已读取的范围
// readIndex -- WriterIndex 可读的范围
// WriterIndex -- capacity 可写的范围
ByteBuf buf = Unpooled.buffer(10);
for (int i = 0; i < 10; i++) {
//每次写一个,writerIndex 向后移一位
buf.writeByte(i);
}
for (int i = 0; i < buf.capacity(); i++) {
//此处没有使用 buf.readByte() 如果使用则 readIndex 向后移一位
System.out.println(buf.getByte(i));;
}
System.out.println("运行结束了!");
LinkedList<Object> queue = new LinkedList<>();
Object o = queue.removeFirst();
}
}
6.10.2、案例二
package com.guiguixia.netty.buf;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.charset.Charset;
/**
* @author wzcstart
* @date 2021/6/27 - 23:44
*/
public class NettyByteBuf02 {
public static void main(String[] args){
ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world!", Charset.forName("utf-8"));
if (byteBuf.hasArray()){
System.out.println("array="+byteBuf.array());//hello,world!
System.out.println("capacity="+byteBuf.capacity());//32
System.out.println("readIndex="+byteBuf.readerIndex());//0
System.out.println("writerIndex="+byteBuf.readerIndex());//12
System.out.println("arrayOffset"+byteBuf.arrayOffset());//0
int len = byteBuf.readableBytes();
System.out.println("len="+len);//12
for (int i = 0; i < len; i++) {
//不改变 readableBytes - readByte()方法会改变
System.out.println((char) byteBuf.getByte(i));
}
System.out.println("读取index=0,len=4,Charset=utf-8 => "+
byteBuf.getCharSequence(0, 4, Charset.forName("utf-8") ));
System.out.println("读取index=4,len=6,Charset=utf-8 => "+
byteBuf.getCharSequence(4, 6, Charset.forName("utf-8") ));
System.out.println("is ok ...");
}
}
}
6.11、Netty群聊系统
6.11.1、GroupChatServer
/**
* @author wzcstart
* @date 2021/6/28 - 22:26
*/
public class GroupChatServer {
private int port;
public GroupChatServer(int port) {
this.port = port;
}
private void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(8);
try {
//构建引导器
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.SO_BACKLOG, 128)//当线程已达到最大连接,可存放的最大已建立TCP三次握手的数量
.childOption(ChannelOption.SO_KEEPALIVE, true)//开启心跳检测活跃
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//获取管道
ChannelPipeline pipeline = ch.pipeline();
//加入字符解码器
pipeline.addLast(new StringDecoder());
//加入字符编码器
pipeline.addLast(new StringEncoder());
//加入自己的处理器
pipeline.addLast(new GroupChatServerChannelHandler());
}
});
ChannelFuture channelFuture = bootstrap.bind(port).sync();
System.out.println("server is ok ...");
//监听关闭事件
channelFuture.channel().closeFuture().sync();
}finally {
//关闭资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception{
new GroupChatServer(7000).run();
}
}
6.11.2、GroupChatServerChannelHandler
/**
* @author wzcstart
* @date 2021/6/28 - 22:39
*/
public class GroupChatServerChannelHandler extends SimpleChannelInboundHandler<String> {
//统一存放所有的channel通道
//GlobalEventExecutor.INSTANCE全局事件处理器单实例
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
//设置时间格式
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
//处理私聊
private static Map<String, Channel> cache = new HashMap<String, Channel>();
//正则
private static Pattern pattern = Pattern.compile(".*-->(.*)}");
//只要连接一建立最先执行的方法
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
//再当前channel 加入到channelGroup之前先将channel上线转发给所有channel
//writeAndFlush 方法会遍历发给channelGroup里所有的channel
channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+" "+sdf.format(new Date())+" 加入聊天\n");
//将当前channel加入到channelGroup
channelGroup.add(channel);
}
//建立连接 - 活跃连接
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//将 port 加入到 cache
String port = ctx.channel().remoteAddress().toString().split(":")[1];
cache.put(port,ctx.channel());
System.out.println(ctx.channel().remoteAddress()+" 上线了~");
}
//非活跃连接
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress()+" 离线了~");
}
//断开连接 - 自动从channelGroup中移除channel
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//将 port 移除 cache
String port = ctx.channel().remoteAddress().toString().split(":")[1];
cache.remove(port);
Channel channel = ctx.channel();
channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+" 离开了\n");
System.out.println("channelGroup size = "+channelGroup.size());
}
//读数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
if (msg.contains("-->")){
String[] res = msg.split("-->");
String group = res[1];
String[] split = group.split(",");
for (String s : split) {
Channel channel = cache.get(s);
channel.writeAndFlush(ctx.channel().remoteAddress()+"-->"+res[0]);
}
return;
}
//获取到当前channel
Channel channel = ctx.channel();
channelGroup.forEach(ch->{
if (ch!=channel){
ch.writeAndFlush(sdf.format(new Date())+"[客户:"+channel.remoteAddress()+"] "+msg);
}else {
channel.writeAndFlush("[发送完成] "+msg);
}
});
}
//捕捉到异常 - 关闭通道
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//关闭通道
ctx.channel().close();
}
}
6.11.3、GroupChatClient
/**
* @author wzcstart
* @date 2021/6/29 - 14:25
*/
public class GroupChatClient {
//连接的主机ip
private String host;
//端口
private int port;
public GroupChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void run() throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//得到pipeline
ChannelPipeline pipeline = ch.pipeline();
//加入编解码器
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new GroupChatClientChannelHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
//获取到channel
Channel channel = channelFuture.channel();
System.out.println("[客户端:"+channel.localAddress()+"]准备好了");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
//通过channel发送信息
channel.writeAndFlush(msg);
}
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception{
new GroupChatClient("127.0.0.1", 7000).run();
}
}
6.11.4、GroupChatClientChannelHandler
/**
* @author wzcstart
* @date 2021/6/29 - 14:48
*/
public class GroupChatClientChannelHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
}
6.11.5、效果展示
![](https://i-blog.csdnimg.cn/blog_migrate/817a50094d6f9cfa6ac182da10d77638.png)
![](https://i-blog.csdnimg.cn/blog_migrate/a082ac2fa9aea6fd11081f99cefe8e7f.png)
![](https://i-blog.csdnimg.cn/blog_migrate/8a4372e1573bb522d3291b41859eb064.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f365426b24c6696c8adde41e8a1f0157.png)