Netty是业界最流行的nio框架之一,Netty 是一个基于 Java NIO 的网络应用框架,它提供了简单易用的 API,帮助开发人员快速构建高性能、可扩展的网络应用程序
Netty的优点:
1.高性能:Netty 使用了异步、事件驱动的方式处理网络通信,可以高效地处理大量并发连接,提供了高性能的网络通信能力。
2.可扩展性:Netty 提供了灵活的、可扩展的架构,支持自定义的编解码器、处理器等组件,使得开发人员能够根据自己的需求定制网络应用。
3.易用性:Netty 提供了简洁而强大的 API,对开发人员友好,降低了开发复杂网络应用的难度。
4.兼容性:Netty 支持多种协议和编解码方式,包括 TCP、UDP、HTTP 等,可以满足各种不同类型的网络应用开发需求。
5.安全性:Netty 提供了一套完善的安全机制,包括 SSL/TLS 支持等,保障网络通信的安全性和稳定性。
6.通讯服务端开发: 可用于智能GSM/GPRS模块的通讯服务端开发,使用它进行MQTT协议的开发。
6.社区活跃:Netty 拥有庞大且活跃的开发者社区,提供了丰富的文档、示例和支持,开发人员可以轻松获取帮助和资源。
1、Netty结合Springboot快速开发框架搭建服务端程序
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.65.Final</version>
</dependency>
2、Springboot启动类,Netty启动
package boot.netty.base.server;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
//import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class BootNettyApplication implements CommandLineRunner{
public static void main( String[] args )
{
/**
* 启动springboot
*/
SpringApplication app = new SpringApplication(BootNettyApplication.class);
//app.setWebApplicationType(WebApplicationType.NONE);//不启动web服务
app.run(args);
System.out.println( "Hello World!" );
}
@Async
@Override
public void run(String... args) throws Exception {
/**
* 使用异步注解方式启动netty服务端服务
*/
new BootNettyServer().bind(8888);
}
}
3、Netty的server类
@Slf4j
@Component
public class BootNettyServer {
public void bind(int port) throws Exception {
/**
* 配置服务端的NIO线程组
* NioEventLoopGroup 是用来处理I/O操作的Reactor线程组
* bossGroup:用来接收进来的连接,workerGroup:用来处理已经被接收的连接,进行socketChannel的网络读写,
* bossGroup接收到连接后就会把连接信息注册到workerGroup
* workerGroup的EventLoopGroup默认的线程数是CPU核数的二倍
*/
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
/**
* ServerBootstrap 是一个启动NIO服务的辅助启动类
*/
ServerBootstrap serverBootstrap = new ServerBootstrap();
/**
* 设置group,将bossGroup, workerGroup线程组传递到ServerBootstrap
*/
serverBootstrap = serverBootstrap.group(bossGroup, workerGroup);
/**
* ServerSocketChannel是以NIO的selector为基础进行实现的,用来接收新的连接,这里告诉Channel通过NioServerSocketChannel获取新的连接
*/
serverBootstrap = serverBootstrap.channel(NioServerSocketChannel.class);
/**
* option是设置 bossGroup,childOption是设置workerGroup
* netty 默认数据包传输大小为1024字节, 设置它可以自动调整下一次缓冲区建立时分配的空间大小,避免内存的浪费最小初始化最大 (根据生产环境实际情况来定)
* 使用对象池,重用缓冲区
*/
serverBootstrap = serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 10496, 1048576));
serverBootstrap = serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 10496, 1048576));
/**
* 设置 I/O处理类,主要用于网络I/O事件,记录日志,编码、解码消息
*/
serverBootstrap = serverBootstrap.childHandler(new BootNettyChannelInitializer<SocketChannel>());
log.info("netty server start success!");
/**
* 绑定端口,同步等待成功
*/
ChannelFuture f = serverBootstrap.bind(port).sync();
/**
* 等待服务器监听端口关闭
*/
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
} finally {
/**
* 退出,释放线程池资源
*/
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
4、通道初始化
/**
* 通道初始化
*/
public class BootNettyChannelInitializer<SocketChannel> extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) throws Exception {
//添加编解码,此处代码为解析tcp传过来的参数,为UTF-8格式,可以自定义解码格式
// ChannelOutboundHandler,依照逆序执行
ch.pipeline().addLast("encoder", new StringEncoder());
// 属于ChannelInboundHandler,依照顺序执行
ch.pipeline().addLast("decoder", new StringDecoder());
/**
* 自定义ChannelInboundHandlerAdapter
*/
ch.pipeline().addLast(new BootNettyChannelInboundHandlerAdapter());
}
}
5、I/O数据读写处理类
@Slf4j
@Component
public class BootNettyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter{
private static BootNettyChannelInboundHandlerAdapter nettyServerHandler;
@PostConstruct
public void init() {
nettyServerHandler = this;
}
@Autowired
private GatewayEquipmentMapper gatewayEquipmentMapper;
/**
* 从客户端收到新的数据时,这个方法会在收到消息时被调用
*
* @param ctx
* @param msg
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception, IOException {
try{
if (msg == null) {
log.error("======加载客户端报文为空======【" + ctx.channel().id() + "】" + " :" + msg);
}
log.info("======加载客户端报文======【" + ctx.channel().id() + "】" + " :" + msg);
JSONObject jsonObject = JSON.parseObject(msg.toString());
// 解析数据
getGateWayData(jsonObject);
//回应客户端
ctx.write(ctx.channel().id()+"服务端已成功接收数据!");
}catch (Exception e){
e.printStackTrace();
}
}
private void getGateWayData(JSONObject jsonObject){
Integer battery = null;//网关电池电量
long time;// 数据生成时间
String gateWayTime = null; // 时间戳转为日期
if (jsonObject.getInteger("battery") != null) {
battery = jsonObject.getInteger("battery");
}
// ......
JSONArray devicesArray = jsonObject.getJSONArray("devices");
log.info("==========解析网关广播数据:"+devicesArray);
}
/**
* 从客户端收到新的数据、读取完成时调用
*
* @param ctx
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws IOException {
log.info("channelReadComplete");
ctx.flush();
}
/**
* 当出现 Throwable 对象才会被调用,即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
*
* @param ctx
* @param cause
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws IOException {
log.info("exceptionCaught");
cause.printStackTrace();
ctx.close();//抛出异常,断开与客户端的连接
}
/**
* 客户端与服务端第一次建立连接时 执行
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException {
super.channelActive(ctx);
ctx.channel().read();
InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = insocket.getAddress().getHostAddress();
//此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
log.info("channelActive:"+clientIp+ctx.name());
}
/**
* 客户端与服务端 断连时 执行
*
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException {
super.channelInactive(ctx);
InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = insocket.getAddress().getHostAddress();
ctx.close(); //断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
log.info("channelInactive:"+clientIp);
}
/**
* 服务端当read超时, 会调用这个方法
*
* @param ctx
* @param evt
* @throws Exception
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException {
super.userEventTriggered(ctx, evt);
InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = insocket.getAddress().getHostAddress();
ctx.close();//超时时断开连接
log.info("userEventTriggered:"+clientIp);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception{
log.info("channelRegistered");
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception{
//当一个客户端断开连接或一个服务器完成其服务并关闭连接时
log.info("channelUnregistered");
}
/**
* 流量控制是一种拥塞控制机制,
* 用于防止发送方过多地发送数据,从而导致接收方过载。
* 当通道变得不可写时,这可能意味着接收方的缓冲区已满,
* 因此发送方需要停止发送数据,等待通道变得可写时再继续发送
* @throws Exception
*/
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception{
// 通道变得可写,可以继续发送数据
log.info("Channel is writable, resuming data transmission.");
}
/**
* 广播数据十六进制,每两个字符为一组,
*如:09 57 79 30 30 30 30 30 30 30 30 30 30 30 41 30 30 35 30 30
* 再转为对应ASCII码,即可得到明文的uuid
* @param uuid
*/
public String hexToASCII(String uuid) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < uuid.length(); i += 2) {
String hex = uuid.substring(i, i + 2);
int decimal = Integer.parseInt(hex, 16);
char asciiChar = (char) decimal;
sb.append(asciiChar);
}
String result = sb.toString();
return result;
}
/**
* 将时间戳转换为yyyy-MM-dd HH:mm:ss格式的日期字符串。
* @param timestamp 时间戳(以毫秒为单位)
* @return 格式化后的日期字符串
*/
public String timestampToDate(long timestamp) {
Instant instant = Instant.ofEpochSecond(timestamp); // 将时间戳转换为Instant对象
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // 将Instant对象转换为本地日期时间对象
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期格式
// 将日期时间对象格式化为字符串
String time = dateTime.format(formatter);
return time;
}
/**
* 将LocalDateTime转换为yyyy-MM-dd HH:mm:ss格式的日期字符串。
* @return 格式化后的日期字符串
*/
public String LocalDateTimeToStr() {
// 获取当前日期时间
LocalDateTime now = LocalDateTime.now();
// 定义日期时间的格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 将LocalDateTime格式化为字符串
String formattedDateTime = now.format(formatter);
return formattedDateTime;
}
}
仅仅四个类就将Springboot和Netty结合,启动Springboot应用的同时也就启动了Netty,端口:8888
可以使用TCP客户端工具: