【Netty4】深入学习Netty

2024-03-29 21:38
文章标签 学习 深入 netty netty4

本文主要是介绍【Netty4】深入学习Netty,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Netty is an asynchronous event-driven network application framework 
for rapid development of maintainable high performance protocol servers & clients

 

学习前,建议了解下java NIO相关知识,有助于对Netty中对象的理解。

NIO介绍,博客地址:https://blog.csdn.net/the_fool_/article/details/83000648

AIO、BIO、NIO的区别,博客地址:https://blog.csdn.net/anxpp/article/details/51512200

Netty如何封装Java NIO,博客地址::https://blog.csdn.net/tjreal/article/details/79751342

应用场景:https://blog.csdn.net/LIAN_XL/article/details/79799072

官网:https://netty.io/

版本:目前最新版本为4.1.30

环境:JDK 5 (Netty 3.x) or 6 (Netty 4.x) is enough

八卦:Netty5被干掉的原因?极大增加了复杂度,效率却没有提升,作者干掉了master分支。

模块,结构:

支持的链接类型:普通链接、长连接、心跳检测等。

使用:官方的简单demo,用于介绍Netty 创建过程:

完整代码:https://blog.csdn.net/the_fool_/article/details/80611148

1、根据实际业务创建handle处理类,处理客户端请求实际信息:

package com.xxx.ann.netty.mostsimple;import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;/*** Handles a server-side channel.* 实际上自定义的业务流程使用的是本类*/
public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)/*** Server读取信息的方法* @param ctx* @param msg*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ByteBuf in = (ByteBuf) msg;try {while (in.isReadable()) { // (1)System.out.print((char) in.readByte());System.out.flush();}// 向客户端发送消息String response = "hello client!";// 在当前场景下,发送的数据必须转换成ByteBuf数组ByteBuf encoded = ctx.alloc().buffer(4 * response.length());encoded.writeBytes(response.getBytes());ctx.write(encoded);ctx.flush();} finally {ReferenceCountUtil.release(msg); // (2)}}/*** 处理异常* @param ctx* @param cause*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)// Close the connection when an exception is raised.cause.printStackTrace();ctx.close();}
}

2、Server 端代码:

package com.xxx.ann.netty.mostsimple;import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;/*** server 端*/
public class DiscardServer {private int port;public DiscardServer(int port){this.port=port;}public void run() throws Exception{/**EventLoopGroup:IO操作的多线程组*boss:* accepts an incoming connection 处理链接*worker:* handles the traffic of the accepted connection once* the boss accepts the connection and registers the accepted* connection to the worker 处理实际逻辑* 使用多少线程以及如何将它们映射到创建的通道取决于EventLoopGroup实现,甚至可以通过构造函数进行配置。* */EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {/**ServerBootstrap是一个建立服务器的助手类。可以直接使用通道设置服务器。*/ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup)/**Here, we specify to use the NioServerSocketChannel class which is used to* instantiate a new Channel to accept incoming connections.*/.channel(NioServerSocketChannel.class)/**** 这里指定处理程序将始终由新接受的通道进行处理* ChannelInitializer:是专门帮助用户配置新通道的特殊处理程序。* 实际使用需要抽取到顶级类并自定义业务逻辑代码*/.childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new DiscardServerHandler());}})/**特定通道实现参数,具体含义:https://netty.io/4.1/api/io/netty/channel/ChannelOption.html*option() is for the NioServerSocketChannel that accepts incoming connections* childOption() is for the Channels accepted by the parent ServerChannel* */.option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);/** Bind and start to accept incoming connections.*/ChannelFuture f = b.bind(port).sync();/*** Wait until the server socket is closed.* In this example, this does not happen, but you can do that to gracefully* shut down your server.* */f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();}finally {workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();}}public static void main(String[] args) throws Exception {int port=8081;new DiscardServer(port).run();}
}

3、浏览器进入licalhost:8081或者telnet localhost 8081可访问服务端,可在控制台查看到已经建立连接并访问成功(本demo不会成功返回数据)。

这篇关于【Netty4】深入学习Netty的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/859711

相关文章

深入理解Apache Kafka(分布式流处理平台)

《深入理解ApacheKafka(分布式流处理平台)》ApacheKafka作为现代分布式系统中的核心中间件,为构建高吞吐量、低延迟的数据管道提供了强大支持,本文将深入探讨Kafka的核心概念、架构... 目录引言一、Apache Kafka概述1.1 什么是Kafka?1.2 Kafka的核心概念二、Ka

Java并发编程必备之Synchronized关键字深入解析

《Java并发编程必备之Synchronized关键字深入解析》本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种... 目录一、前言二、Synchronized关键字2.1 Synchronized的特性1. 互斥2.

Java的IO模型、Netty原理解析

《Java的IO模型、Netty原理解析》Java的I/O是以流的方式进行数据输入输出的,Java的类库涉及很多领域的IO内容:标准的输入输出,文件的操作、网络上的数据传输流、字符串流、对象流等,这篇... 目录1.什么是IO2.同步与异步、阻塞与非阻塞3.三种IO模型BIO(blocking I/O)NI

一文带你深入了解Python中的GeneratorExit异常处理

《一文带你深入了解Python中的GeneratorExit异常处理》GeneratorExit是Python内置的异常,当生成器或协程被强制关闭时,Python解释器会向其发送这个异常,下面我们来看... 目录GeneratorExit:协程世界的死亡通知书什么是GeneratorExit实际中的问题案例

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

深入理解Apache Airflow 调度器(最新推荐)

《深入理解ApacheAirflow调度器(最新推荐)》ApacheAirflow调度器是数据管道管理系统的关键组件,负责编排dag中任务的执行,通过理解调度器的角色和工作方式,正确配置调度器,并... 目录什么是Airflow 调度器?Airflow 调度器工作机制配置Airflow调度器调优及优化建议最

深入理解C语言的void*

《深入理解C语言的void*》本文主要介绍了C语言的void*,包括它的任意性、编译器对void*的类型检查以及需要显式类型转换的规则,具有一定的参考价值,感兴趣的可以了解一下... 目录一、void* 的类型任意性二、编译器对 void* 的类型检查三、需要显式类型转换占用的字节四、总结一、void* 的

深入理解Redis大key的危害及解决方案

《深入理解Redis大key的危害及解决方案》本文主要介绍了深入理解Redis大key的危害及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录一、背景二、什么是大key三、大key评价标准四、大key 产生的原因与场景五、大key影响与危