文章目录
1、Netty解决的痛点
- NIO的类库和API复杂,需要对Selector、ServerSocketChannel、SocketChannel、ByteBuffer等做操作。
- 针对客户端断线重连、网络闪断、线条处理、半包读写、网络拥塞、异常等分别处理。
- Netty对JDK自带的API做了封装,能够解决上述问题。
- Netty拥有高性能、高吞吐、低时延等优点。
2、Netty的使用场景
- 分布式系统中,各节点间远程服务调用需要高性能的RPC框架。Netty作为优秀的异步高性能通信框架,往往作为基础通信组件。
- 阿里分布式框架Dobbo进行节点通信,使用Netty进行进程间通信。
- RocketMQ使用Netty作为基础通信组件
- 华为分布式服务框架servicecomb的Edge Service的是基于Netty的vertx作为基础通信组件
- 游戏行业,通过Netty作为高性能基础通信组件,提供TCP/UDP和http协议栈
- 大数据领域,hadoop高性能通信和序列化Avro的RPC框架,默认采用Netty进行跨界点通信。
3、客户端、服务端demo
先跑demo后,了解基本功能,后看源码。
<!--Netty-->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.73.Final</version>
</dependency>
客户端:
import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
//客户端事件循环组 默认线程数为 cpu-core*2
NioEventLoopGroup group = new NioEventLoopGroup(1);
try {
Bootstrap bootstrap = new Bootstrap();
//设置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("netty client start...");
ChannelFuture cf = bootstrap.connect("127.0.0.1", 9090);
//启动客户端连接服务器
cf.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
/**
* 建连完成
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("HelloServer".getBytes(CharsetUtil.UTF_8));
ctx.writeAndFlush(buf);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
System.out.println("收到服务端的消息:" + buf.toString(CharsetUtil.UTF_8));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("数据流读取完毕");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("捕获异常"+cause);
}
}
服务端:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io<

Netty是一款高性能、异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。它解决了Java NIO API的复杂性,提供了一套强大的服务端和客户端启动类、线程模型、模块组件,广泛应用于分布式系统、RPC框架、游戏服务器和大数据等领域。Netty的线程模型基于多线程主从反应器设计,确保高效且稳定地处理网络IO事件。此外,文中还展示了Netty的客户端和服务端示例代码,以及如何利用Netty实现聊天室功能。
最低0.47元/天 解锁文章
1154

被折叠的 条评论
为什么被折叠?



