网络开发的最强大框架:Netty快速入门

简介: Netty是一个异步的,基于事件驱动的网络应用框架,用于快速开发可维护、高性能的网络服务器和客户端。Netty的应用十分广泛,可以说主流的框架中,如果有网络方面的需求,一般用的都是netty框架。比如Dubbo、ES、Zookeeper中都用到了Netty。因此即使在平常工作中没有Netty的使用场景,Netty还是十分值得我们去学习的。

听说微信搜索《Java鱼仔》会变更强哦!


本文收录于JavaStarter ,里面有我完整的Java系列文章,学习或面试都可以看看哦


(一)什么是netty


Netty是一个异步的,基于事件驱动的网络应用框架,用于快速开发可维护、高性能的网络服务器和客户端。Netty的应用十分广泛,可以说主流的框架中,如果有网络方面的需求,一般用的都是netty框架。比如DubboESZookeeper中都用到了Netty。因此即使在平常工作中没有Netty的使用场景,Netty还是十分值得我们去学习的。


Netty底层基于NIO开发,其实大部分的Java程序员对于网络方面的开发能力是比较弱的,因此如果有网络相关的开发业务,如果自己通过BIO或者NIO实现,会产生很多问题。而通过Netty可以快速开发网络应用,因此也有人把Netty称为网络开发框架中的Spring


关于NIO和BIO的区别,我之前在博客中也讲到过,BIO每次通信都要新建一个线程去处理,NIO通过多路复用的方式去处理请求。下图就是NIO的处理流程。


网络异常,图片无法展示
|


(二)第一个netty入门程序


既然基于NIO开发,netty的入门程序和我们当时写的nio入门程序比较像,首先开发一个服务器端,netty的开发流程可以遵循一套规范:


1、通过ServerBootstrap启动,组装netty组件


2、组装eventLoopGroup


3、组装Channel


4、通过handler处理连接、读写请求



publicclassFirstServer {
publicstaticvoidmain(String[] args) {
// 1、服务器端的启动器,组装netty组件newServerBootstrap()
//2、组装eventLoop组                .group(newNioEventLoopGroup())
//3、选择服务器的ServerSocketChannel实现                .channel(NioServerSocketChannel.class)
//4、负责处理连接和读写                .childHandler(newChannelInitializer<NioSocketChannel>() {
@OverrideprotectedvoidinitChannel(NioSocketChannelnioSocketChannel) throwsException {
//将bytebuffer转换为字符串nioSocketChannel.pipeline().addLast(newStringDecoder());
//自定义handler,这里接收读事件后展示数据nioSocketChannel.pipeline().addLast(newChannelInboundHandlerAdapter(){
@OverridepublicvoidchannelRead(ChannelHandlerContextctx, Objectmsg) throwsException {
System.out.println(msg);
                            }
                        });
                    }
                })
//5、监听端口                .bind(8080);
    }
}

接着开发一个客户端,客户端的整体流程和服务器端十分类似:


1、通过Bootstrap启动,组装netty组件


2、组装eventLoopGroup


3、组装Channel


4、添加handler处理器


5、建立连接


6、发送数据到服务端


publicclassFirstClient {
publicstaticvoidmain(String[] args) throwsInterruptedException {
//1、启动类newBootstrap()
//2、添加EventLoop组                .group(newNioEventLoopGroup())
//3、添加channel                .channel(NioSocketChannel.class)
//4、添加处理器                .handler(newChannelInitializer<NioSocketChannel>() {
@OverrideprotectedvoidinitChannel(NioSocketChannelnioSocketChannel) throwsException {
//将发送的内容encode编码nioSocketChannel.pipeline().addLast(newStringEncoder());
                    }
                })
//5、连接到服务器                .connect(newInetSocketAddress("localhost",8080))
                .sync()
                .channel()
//6、发送数据                .writeAndFlush("hello");
    }
}

启动服务器端后再启动客户端,可以发现服务端接受到了客户端发过来的信息。看到这里觉得还是有点蒙没关系,下面会对每个组件进行讲解。


(三)理解Netty中的组件


3.1 EventLoop


EventLoop其实是一个单线程的执行器,同时维护了一个Selector,EventLoop的作用是处理Channel上的io事件。


3.2 EventLoopGroup


EventLoopGroup是一组EventLoop,Channel通常会调用EventLoopGroup中的register方法绑定其中的一个EventLoop,后续这个channel中的io事件则都由这个EventLoop处理。


3.3 channel


channel是一个数据的传输流,channel可以理解为是通讯的载体。


3.4 ChannelHandler


ChannelHandler是用来处理Channel上的各种事件的,所有的ChannelHandler连起来就是pipeline。简单来讲,channel是数据的传输通道,而ChannelHandler用来处理通道中的数据。


3.5 ByteBuf


ByteBuf是netty中数据的传输载体,网络数据的基本单位总是字节,ByteBuf用来传输这些网络上的字节。


(四)EventLoop


EventLoop可以处理多种任务,单独使用EventLoop可以通过下面几个步骤实现:

1、创建一个EventLoopGroup


2、从EventLoopGroup中获取EventLoop


3、通过EventLoop执行任务


通过代码这样表示:



publicclassTestEventLoop {
publicstaticvoidmain(String[] args) {
//1、创建事件循环组//NioEventLoopGroup可以处理IO事件、普通任务、定时任务EventLoopGroupgroup=newNioEventLoopGroup();
//2、获取下一个事件循环对象EventLoopeventLoop=group.next();
//3、执行普通任务eventLoop.execute(()->{
System.out.println("普通任务");
        });
//4、执行定时任务eventLoop.scheduleAtFixedRate(()->{
System.out.println("定时任务");
        },0,1, TimeUnit.SECONDS);
    }
}

EventLoop最常用的就是执行IO任务了,我们在入门程序中写的group(new NioEventLoopGroup())就是把EventLoop用来处理IO任务。


在netty中,我们还会在绑定group时指定bosswork,boss用来处理连接,work用来处理收到读写请求后续的操作,有的时候我们还可以自定义EventLoopGroup处理其他任务,因此前面的FirstServer 可以写成下面这样:

publicclassNioServer {
publicstaticvoidmain(String[] args) {
//boss用来处理连接NioEventLoopGroupbossGroup=newNioEventLoopGroup();
//work用来处理读写请求NioEventLoopGroupworkGroup=newNioEventLoopGroup();
//otherGroup处理普通任务,比如打印一段内容EventLoopGroupotherGroup=newDefaultEventLoop();
newServerBootstrap()
                .group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(newChannelInitializer<NioSocketChannel>() {
@OverrideprotectedvoidinitChannel(NioSocketChannelnioSocketChannel) throwsException {
nioSocketChannel.pipeline().addLast(newChannelInboundHandlerAdapter(){
@OverridepublicvoidchannelRead(ChannelHandlerContextctx, Objectmsg) throwsException {
ByteBufbyteBuf= (ByteBuf) msg;
System.out.println(byteBuf.toString());
ctx.fireChannelRead(msg); //将msg传给下一个处理者                            }
                        })
                        .addLast(otherGroup,"handler",newChannelInboundHandlerAdapter(){
@OverridepublicvoidchannelRead(ChannelHandlerContextctx, Objectmsg) throwsException {
ByteBufbyteBuf= (ByteBuf) msg;
System.out.println(byteBuf.toString());
                            }
                        });
                    }
                }).bind(8080);
    }
}

(五)Channel


Channel中有几个常用的方法:


close() 关闭channelpipeline() 添加处理器write() 将数据写入到缓冲区flush() 将数据刷出,也就是发给服务端writeAndFlush() 将数据写入并刷出

我们通过入门案例的客户端代码讲解Channel


5.1 channel的连接


publicclassNioClient  {
publicstaticvoidmain(String[] args) throwsInterruptedException {
ChannelFuturechannelFuture=newBootstrap()
                .group(newNioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(newChannelInitializer<NioSocketChannel>() {
@OverrideprotectedvoidinitChannel(NioSocketChannelnioSocketChannel) throwsException {
nioSocketChannel.pipeline().addLast(newStringEncoder());
                    }
                })
//connect是一个异步调用的过程,因此必须要使用sync方法等待连接建立                .connect(newInetSocketAddress("localhost", 8080));
//1、使用sync方法阻塞线程直到连接建立channelFuture.sync();
channelFuture.channel().writeAndFlush("hello,world");
    }
}


整个流程这里就不介绍了,主要介绍里面的一个方法 channelFuture.sync(); 当调用connect方法建立连接时,这个connect方法其实是一个异步的方法,因此如果不加 channelFuture.sync()方法等待连接建立,是无法获取到连接后的channel的,更别提写入数据了。


除了使用sync等待连接,还可以采用设置监听器的方式获取channelFuture


publicstaticvoidmain(String[] args) throwsInterruptedException {
ChannelFuturechannelFuture=newBootstrap()
            .group(newNioEventLoopGroup())
            .channel(NioSocketChannel.class)
            .handler(newChannelInitializer<NioSocketChannel>() {
@OverrideprotectedvoidinitChannel(NioSocketChannelnioSocketChannel) throwsException {
nioSocketChannel.pipeline().addLast(newStringEncoder());
                }
            })
//connect是一个异步调用的过程,因此必须要使用sync方法等待连接建立            .connect(newInetSocketAddress("localhost", 8080));
//2、使用addListener方法异步处理结果channelFuture.addListener(newChannelFutureListener() {
//在nio连接建立完毕之后,调用operationComplete方法@OverridepublicvoidoperationComplete(ChannelFuturechannelFuture) throwsException {
Channelchannel=channelFuture.channel();
channel.writeAndFlush("hello,world");
        }
    });
}

思路是一样的,等连接建立之后再处理对应的方法。


5.2 channel的关闭


除了连接是异步方法之外,channel的关闭方法也是异步的,因此也需要通过


同步阻塞的方式等待关闭:Channelchannel=channelFuture.channel();
ChannelFuturecloseFuture=channel.closeFuture();
System.out.println("等待关闭中");
//当其他线程关闭了channel,sync同步等待closeFuture.sync();
System.out.println("连接已关闭");

同样也可以采用监听器回调的方式:

Channelchannel=channelFuture.channel();
ChannelFuturecloseFuture=channel.closeFuture();
closeFuture.addListener(newChannelFutureListener() {
@OverridepublicvoidoperationComplete(ChannelFuturechannelFuture) throwsException {
System.out.println("连接已关闭");
    }
});

(六)ChannelHandler


ChannelHandler是用来处理Channel上的各种事件的,handler分为inboundoutbount两种,所有的ChannelHandler连起来就是pipeline


ChannelInboundHandlerAdapter的子类主要用来读取客户端数据,写回结果。

ChannelOutboundHandlerAdapter的字类主要对写回结果进行加工。


关于handler和pipeline的代码在前面的例子中都有写


publicstaticvoidmain(String[] args) {
newServerBootstrap()
            .group(newNioEventLoopGroup())
            .channel(NioServerSocketChannel.class)
            .childHandler(newChannelInitializer<NioSocketChannel>() {
@OverrideprotectedvoidinitChannel(NioSocketChannelnioSocketChannel) throwsException {
//1、从channel中获取到pipelineChannelPipelinepipeline=nioSocketChannel.pipeline();
//2、添加handler处理器到pipelinepipeline.addLast(newChannelInboundHandlerAdapter(){
@OverridepublicvoidchannelRead(ChannelHandlerContextctx, Objectmsg) throwsException {
ByteBufbyteBuf= (ByteBuf) msg;
System.out.println(byteBuf.toString());
ctx.fireChannelRead(msg); //将msg传给下一个处理者                        }
                    });
//3、添加多个表示依次执行pipeline.addLast(newChannelInboundHandlerAdapter(){
@OverridepublicvoidchannelRead(ChannelHandlerContextctx, Objectmsg) throwsException {
ByteBufbyteBuf= (ByteBuf) msg;
System.out.println(byteBuf.toString());
                        }
                    });
                }
            }).bind(8080);

(七)ByteBuf


netty中的ByteBuf比JDK自带的ByteBuffer对字节数据的操作更加友好,也更加强大。ByteBuf的主要优势有几下几点:


1、支持自动扩容


2、支持池化技术,可以重用实例,节约内存


3、读写指针分离


4、很多方法体现了零拷贝,比如slice、duplicate等


接下来通过一些操作带你来了解ByteBuf。

1、自动扩容



创建一个默认的ByteBuf,初始容量是256,写入一系列数据之后,这个容量会随着数据的增大自动扩容。


publicstaticvoidmain(String[] args) {
ByteBufbuf=ByteBufAllocator.DEFAULT.buffer();
System.out.println(buf);
StringBuilderstringBuilder=newStringBuilder();
for (inti=0; i<500; i++) {
stringBuilder.append("1");
    }
buf.writeBytes(stringBuilder.toString().getBytes());
System.out.println(buf);
}

结果:

PooledUnsafeDirectByteBuf(ridx: 0, widx: 0, cap: 256)
PooledUnsafeDirectByteBuf(ridx: 0, widx: 500, cap: 512)

ByteBuf的扩容规则如下:


如果数据大小没有超过512,每次扩容到16的整数倍


如果数据大小超过512,则扩容到下一个2^n次


扩容不能超过max capacity


2、直接内存和堆内存



ByteBuf支持创建基于直接内存的ByteBuf,也支持创建基于堆内存的ByteBuf。两者的差距在于:


堆内存的分配效率较高,但是读写性能相对比较低。


直接内存的分配效率比较低,但是读写性能较高(少一次内存复制)

netty默认使用直接内存作为创建ByteBuf的方式



ByteBufAllocator.DEFAULT.heapBuffer();
ByteBufAllocator.DEFAULT.directBuffer();

3、池化技术


ByteBuf支持池化技术,所谓池化指的是ByteBuf创建出来后可以重用,节约内存。通过JVM参数开启或关闭netty的池化,默认开启状态:


-Dio.netty.allocator.type={unpooled|pooled}

(八)总结


Netty是个很强大的框架,但是网络开发本就是一件比较复杂的事情,接下来我会用Netty做一些简单的应用出来,通过这些应用会让Netty更加容易理解一些。我是鱼仔,我们下期再见!

相关文章
|
3月前
|
数据采集 存储 数据处理
Scrapy:Python网络爬虫框架的利器
在当今信息时代,网络数据已成为企业和个人获取信息的重要途径。而Python网络爬虫框架Scrapy则成为了网络爬虫工程师的必备工具。本文将介绍Scrapy的概念与实践,以及其在数据采集和处理过程中的应用。
23 1
|
3月前
|
NoSQL Linux Redis
Redis 的网络框架是实现了 Reactor 模型吗?
Redis 的网络框架是实现了 Reactor 模型吗?
|
13天前
|
网络协议 Java API
Python网络编程基础(Socket编程)Twisted框架简介
【4月更文挑战第12天】在网络编程的实践中,除了使用基本的Socket API之外,还有许多高级的网络编程库可以帮助我们更高效地构建复杂和健壮的网络应用。这些库通常提供了异步IO、事件驱动、协议实现等高级功能,使得开发者能够专注于业务逻辑的实现,而不用过多关注底层的网络细节。
|
存储 设计模式 网络协议
Netty网络框架(一)
Netty网络框架
31 1
|
1月前
|
前端开发 Java 数据库连接
探索Java中最常用的框架:Spring、Spring MVC、Spring Boot、MyBatis和Netty
探索Java中最常用的框架:Spring、Spring MVC、Spring Boot、MyBatis和Netty
|
1月前
|
缓存 网络协议 Linux
性能工具之网络 Benchmark iperf3 快速入门
Benchmark 评估服务器之前的网络带宽简单方法,大家做性能测试是否也是这样评估网络带宽?
36 2
性能工具之网络 Benchmark iperf3 快速入门
|
1月前
|
网络协议 安全 网络安全
网络基础与通信原理:构建数字世界的框架
网络基础与通信原理:构建数字世界的框架
46 1
|
2月前
|
前端开发 Java 数据库连接
认识Java中最常用的框架:Spring、Spring MVC、Spring Boot、MyBatis和Netty
Spring框架 Spring是一个轻量级的开源框架,用于构建企业级应用。它提供了广泛的功能,包括依赖注入、面向切面编程、事务管理、消息传递等。Spring的核心思想是控制反转(IoC)和面向切面编程(AOP)。
78 3
|
3月前
|
负载均衡 Java 调度
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(Dispatcher和EventListener)(下)
经过阅读《【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)》,相信您已经对网络通信框架的网络通信层的实现原理和协议模型有了一定的认识和理解。
40 0
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(Dispatcher和EventListener)(下)
|
3月前
|
Dubbo Java 应用服务中间件
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)
今天,我要向大家实现一个基于Netty实现的高性能远程通信框架!这个框架利用了 Netty 的强大功能,提供了快速、可靠的远程通信能力。 无论是构建大规模微服务架构还是实现分布式计算,这个分布式通信框架都是一个不可或缺的利器。
64 2
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)