Netty的简介与实战
Netty简介
一、背景与来源
- Netty最初是由JBOSS提供的一个Java开源框架,现在已成为Github上的独立项目。
- 它基于Java的NIO(New Input/Output)模型,提供了简单而强大的抽象,使得网络编程变得更加容易和高效。
二、特点与优势
- 高性能:Netty使用高效的Reactor模式,采用非阻塞I/O操作,以及优化的内存管理和缓冲区池,确保了高性能的数据处理和传输。与其他业界主流的NIO框架相比,Netty在吞吐量、延迟、资源消耗等方面都表现出色。
- 异步事件驱动:Netty基于事件驱动模型,能够轻松处理并发连接和高吞吐量的数据传输。它处理连接、读写、异常等事件,并通过事件处理器将这些事件传递给应用程序,使开发者能够集中处理业务逻辑。
- 支持多种协议:Netty支持多种传输协议,包括TCP、UDP、HTTP、HTTPS、WebSocket、Google Protocol Buffers等,还可以通过扩展支持其他自定义协议。这使得开发者能够更轻松地处理不同协议的网络通信。
- 可扩展性:Netty提供了灵活的Pipeline机制,允许开发者通过ChannelHandler链来处理网络事件,实现自定义的编解码器、拦截器等组件。通过这种模块化的设计,可以轻松扩展和定制Netty的功能。
- 易用性:Netty提供了简洁的API和详细的文档,使得开发者能够快速上手和实现复杂的网络功能。同时,Netty的社区非常活跃,有大量的资源和经验可供参考。
- 跨平台:Netty可运行在多种操作系统和Java版本上,保证了良好的跨平台兼容性。
三、核心组件与功能
Netty框架主要由以下几个核心组件构成,这些组件共同构建了Netty的整体架构,分别负责处理不同的功能和逻辑:
- Channel:Channel是Netty中的基本抽象,代表一个连接或通信的载体,可以是TCP连接、UDP套接字等。Channel负责I/O操作的执行,并维护连接的状态。
- EventLoop:EventLoop是Netty中的事件循环,负责处理I/O操作和任务调度。每个EventLoop都与一个线程关联,并分配给一个或多个Channel。EventLoop负责将事件分发给对应的ChannelHandler进行处理。
- ChannelHandler:ChannelHandler是Netty中的处理器接口,负责处理网络事件,如连接建立、数据读写、异常处理等。开发者可以实现自定义的ChannelHandler以处理特定的业务逻辑。
- ChannelPipeline:ChannelPipeline是一个ChannelHandler的链表,负责管理和调度ChannelHandler。当一个网络事件发生时,ChannelPipeline会按照链表顺序将事件传递给各个ChannelHandler,直到其中一个处理器处理了事件或者到达链表尾部。
- ChannelHandlerContext:ChannelHandlerContext是ChannelHandler与ChannelPipeline之间的桥梁,允许ChannelHandler与Pipeline以及其他Handler进行交互。通过ChannelHandlerContext,Handler可以访问Channel、Pipeline,以及发送事件给其他Handler。
- ByteBuf:ByteBuf是Netty中的字节缓冲区,用于存储和处理字节数据。相较于Java的ByteBuffer,ByteBuf提供了更高效的内存管理和更简洁的API,支持自动扩容、复合缓冲区等特性。
- Bootstrap:Bootstrap是Netty中的启动类,用于配置和启动客户端或服务器。通过Bootstrap,开发者可以设置Channel的初始化参数、事件处理器等,以及绑定端口和启动监听。
四、应用场景与实例
Netty被广泛应用于分布式系统、实时通信、游戏开发等场景。例如,RocketMQ、Elasticsearch、Dubbo等知名的开源项目和大型企业都使用了Netty作为底层网络通信框架。这些应用通过Netty的高性能和灵活的设计,实现了高效、可靠的网络通信。
实战
netty服务器
@Component
public class NettyServer {
static final Logger log = LoggerFactory.getLogger(NettyServer.class);
/**
* 端口号
*/
@Value("${webSocket.netty.port:8888}")
int port;
EventLoopGroup bossGroup;
EventLoopGroup workGroup;
@Autowired
ProjectInitializer nettyInitializer;
@PostConstruct
public void start() throws InterruptedException {
new Thread(() -> {
bossGroup = new NioEventLoopGroup();
workGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
// bossGroup辅助客户端的tcp连接请求, workGroup负责与客户端之前的读写操作
bootstrap.group(bossGroup, workGroup);
// 设置NIO类型的channel
bootstrap.channel(NioServerSocketChannel.class);
// 设置监听端口
bootstrap.localAddress(new InetSocketAddress(port));
// 设置管道
bootstrap.childHandler(nettyInitializer);
// 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功
ChannelFuture channelFuture = null;
try {
channelFuture = bootstrap.bind().sync();
log.info("Server started and listen on:{}", channelFuture.channel().localAddress());
// 对关闭通道进行监听
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
/**
* 释放资源
*/
@PreDestroy
public void destroy() throws InterruptedException {
if (bossGroup != null) {
bossGroup.shutdownGracefully().sync();
}
if (workGroup != null) {
workGroup.shutdownGracefully().sync();
}
}
}
Netty配置
管理全局Channel以及用户对应的channel(推送消息)
public class NettyConfig {
/**
* 定义全局单利channel组 管理所有channel
*/
private static volatile ChannelGroup channelGroup = null;
/**
* 存放请求ID与channel的对应关系
*/
private static volatile ConcurrentHashMap<String, Channel> channelMap = null;
/**
* 定义两把锁
*/
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static ChannelGroup getChannelGroup() {
if (null == channelGroup) {
synchronized (lock1) {
if (null == channelGroup) {
channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}
}
}
return channelGroup;
}
public static ConcurrentHashMap<String, Channel> getChannelMap() {
if (null == channelMap) {
synchronized (lock2) {
if (null == channelMap) {
channelMap = new ConcurrentHashMap<>();
}
}
}
return channelMap;
}
public static Channel getChannel(String userId) {
if (null == channelMap) {
return getChannelMap().get(userId);
}
return channelMap.get(userId);
}
}
管道配置
@Component
public class ProjectInitializer extends ChannelInitializer<SocketChannel> {
/**
* webSocket协议名
*/
static final String WEBSOCKET_PROTOCOL = "WebSocket";
/**
* webSocket路径
*/
@Value("${webSocket.netty.path:/webSocket}")
String webSocketPath;
@Autowired
WebSocketHandler webSocketHandler;
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// 设置管道
ChannelPipeline pipeline = socketChannel.pipeline();
// 流水线管理通道中的处理程序(Handler),用来处理业务
// webSocket协议本身是基于http协议的,所以这边也要使用http编解码器
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ObjectEncoder());
// 以块的方式来写的处理器
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler(webSocketPath, WEBSOCKET_PROTOCOL, true, 65536 * 10));
// 自定义的handler,处理业务逻辑
pipeline.addLast(webSocketHandler);
}
}
自定义handler
@Component
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
/**
* 一旦连接,第一个被执行
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
log.info("有新的客户端链接:[{}]", ctx.channel().id().asLongText());
// 添加到channelGroup 通道组
NettyConfig.getChannelGroup().add(ctx.channel());
}
/**
* 读取数据
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
log.info("服务器收到消息:{}", msg.text());
// 获取用户ID,关联channel
JSONObject jsonObject = JSONUtil.parseObj(msg.text());
String uid = jsonObject.getStr("uid");
NettyConfig.getChannelMap().put(uid, ctx.channel());
// 将用户ID作为自定义属性加入到channel中,方便随时channel中获取用户ID
AttributeKey<String> key = AttributeKey.valueOf("userId");
ctx.channel().attr(key).setIfAbsent(uid);
// 回复消息
ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器收到消息啦"));
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
log.info("用户下线了:{}", ctx.channel().id().asLongText());
// 删除通道
NettyConfig.getChannelGroup().remove(ctx.channel());
removeUserId(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.info("异常:{}", cause.getMessage());
// 删除通道
NettyConfig.getChannelGroup().remove(ctx.channel());
removeUserId(ctx);
ctx.close();
}
/**
* 删除用户与channel的对应关系
*/
private void removeUserId(ChannelHandlerContext ctx) {
AttributeKey<String> key = AttributeKey.valueOf("userId");
String userId = ctx.channel().attr(key).get();
NettyConfig.getChannelMap().remove(userId);
}
}
推送消息接口及实现类
public interface PushMsgService {
/**
* 推送给指定用户
*/
void pushMsgToOne(String userId, String msg);
/**
* 推送给所有用户
*/
void pushMsgToAll(String msg);
}
@Service
public class PushMsgServiceImpl implements PushMsgService {
@Override
public void pushMsgToOne(String userId, String msg) {
Channel channel = NettyConfig.getChannel(userId);
if (Objects.isNull(channel)) {
throw new RuntimeException("未连接socket服务器");
}
channel.writeAndFlush(new TextWebSocketFrame(msg));
}
@Override
public void pushMsgToAll(String msg) {
NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));
}
}