SpringBoot 2.7 集成 Netty 4 解决粘包半包问题

1 摘要

Netty 的粘包和半包问题是由于 Netty 在接收消息时无法判断消息是否发送完毕,只能靠读取消息时是否读满缓存来终止,因此就出现了连续发送多条消息,实际上 Netty 接收端只在一次读取这就是粘包;又或者一次发送的消息太长,读取的时候会丢弃一部分,这就是半包。为了解决这个问题,保证一次发送对应一次读取,类似于 http 请求,一次请求对应一次回复。这里介绍使用LengthFieldBasedFrameDecoder解决 Netty 粘包半包问题。

关于 LengthFieldBasedFrameDecoder 解码器类,这是用来确定接收端如何读取消息的,数据会请求头+请求体,请求头部分用来存放固定字段以及请求体的长度,在读取消息的时候拿到字段的长度来读取对应的消息体,这样就能完整地区分一条消息。

解码器需要与编码器搭配,LengthFieldPrepender 即为编码器,指在发送消息的时候添加固定长度消息头。

关于 Netty 入门教程,可参考:

SpringBoot 2.7 集成 Netty 4 模拟服务端与客户端通讯入门教程

2 核心代码

2.1 Netty 服务端连接器

demo-netty-server/src/main/java/com/ljq/demo/springboot/netty/server/init/InitStrongNettyServer.java
package com.ljq.demo.springboot.netty.server.init;

import com.ljq.demo.springboot.netty.server.handler.DemoStrongNettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * @Description: 强化版 netty 服务端
 * @Author: junqiang.lu
 * @Date: 2023/8/23
 */
@Slf4j
@Component
public class InitStrongNettyServer implements ApplicationRunner {

    @Value("${netty.port2:9125}")
    private Integer nettyPort;


    @Resource
    private DemoStrongNettyServerHandler nettyServerHandler;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.start();
    }

    /**
     * 启动服务
     *
     * @throws InterruptedException
     */
    public void start() throws InterruptedException {
        // 连接管理线程池
        EventLoopGroup mainGroup = new NioEventLoopGroup(2);
        // 工作线程池
        EventLoopGroup workGroup = new NioEventLoopGroup(8);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(mainGroup, workGroup)
                // 指定 nio 通道
                .channel(NioServerSocketChannel.class)
                // 指定 socket 地址和端口
                .localAddress(new InetSocketAddress(nettyPort))
                // 添加子通道 handler
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                // 消息解码: 读取消息头和消息体
                                .addLast(new LengthFieldBasedFrameDecoder(4096, 0, 4, 0, 4))
                                // 消息编码: 将消息封装为消息头和消息体,在响应字节数据前面添加消息体长度
                                .addLast(new LengthFieldPrepender(4))
                                // 字符串编解码器
                                .addLast(new StringEncoder())
                                .addLast(new StringDecoder())
                                .addLast(nettyServerHandler);
                    }
                });
        // 异步绑定服务器,调用sync()方法阻塞等待直到绑定完成
        bootstrap.bind().sync();
        log.info("---------- [init] strong netty server start ----------");
    }
}

代码说明: new LengthFieldBasedFrameDecoder(4096, 0, 4, 0, 4) 指的是一次读取消息的最大长度是 4096 字节,消息长度字段为 4 个字节。

new LengthFieldPrepender(4) 指的是再发送消息时将前边 4 个字节来表示消息的长度。

注意事项:

                // 添加子通道 handler
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                // 消息解码: 读取消息头和消息体
                                .addLast(new LengthFieldBasedFrameDecoder(4096, 0, 4, 0, 4))
                                // 消息编码: 将消息封装为消息头和消息体,在响应字节数据前面添加消息体长度
                                .addLast(new LengthFieldPrepender(4))
                                // 字符串编解码器
                                .addLast(new StringEncoder())
                                .addLast(new StringDecoder())
                                .addLast(nettyServerHandler);

以上编解码的顺序一定不能错,定义消息读取的编解码器一定是放在最开始,如果不这样,依旧会出现粘包半包问题。

2.2 Netty 客户端连接器

demo-netty-server/src/main/java/com/ljq/demo/springboot/netty/server/client/DemoStrongNettyClient.java
package com.ljq.demo.springboot.netty.server.client;

import com.ljq.demo.springboot.netty.server.handler.DemoStrongNettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @Description: 强化版 Netty 客户端模拟器
 * @Author: junqiang.lu
 * @Date: 2023/8/23
 */
@Slf4j
public class DemoStrongNettyClient {

    private final String host;

    private final int port;

    private final EventLoopGroup mainGroup;

    private final Bootstrap bootstrap;

    private Channel channel;

    public DemoStrongNettyClient(String host, int port) {
        this.host = host;
        this.port = port;
        this.mainGroup = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();

    }

    public Channel getChannel() {
        return this.channel;
    }

    /**
     * 创建连接
     */
    public void connect() throws InterruptedException {
        bootstrap.group(mainGroup)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                // 消息解码: 读取消息头和消息体
                                .addLast(new LengthFieldBasedFrameDecoder(4096,0,4,0,4))
                                // 消息编码: 将消息封装为消息头和消息体,在响应字节数据前面添加消息体长度
                                .addLast(new LengthFieldPrepender(4))
                                // 字符串编解码器
                                .addLast(new StringEncoder())
                                .addLast(new StringDecoder())
                                .addLast(new DemoStrongNettyClientHandler());
                    }
                });
        ChannelFuture future = bootstrap.connect().sync();
        this.channel = future.channel();
    }

    /**
     * 发送消息
     *
     * @param message
     */
    public void sendMessage(String message) {
        log.info("客户端待发送消息:{}", message);
        Channel channel = this.getChannel();
        channel.writeAndFlush(message);
    }

    public void close() throws InterruptedException {
        log.info("关闭客户端");
        mainGroup.shutdownGracefully();
    }


    public static void main(String[] args) throws InterruptedException {
        String serverHost = "127.0.0.1";
        int serverPort = 9125;
        String message = "abcde啊哈哈哈";
        DemoStrongNettyClient nettyClient = new DemoStrongNettyClient(serverHost, serverPort);
        nettyClient.connect();
        for (int i = 0; i < 100000; i++) {
            nettyClient.sendMessage(message + i);
        }
        log.info("--------开始休眠 5 秒------------");
        Thread.sleep(5000L);
        log.info("--------休眠 5 秒结束------------");
        for (int i = 0; i < 5; i++) {
            nettyClient.sendMessage(i + message);
            Thread.sleep(100L);
        }
        nettyClient.close();
    }

}

代码说明:编解码器一定是客户端与服务端搭配使用的。

这里也添加了测试方法,实测单机 10W 并发没有问题。

2.3 Netty 服务端 Handler

Handler 这里也贴出来,主要是推荐使用线程池来异步处理事务,这样可以提高并发性能。

demo-netty-server/src/main/java/com/ljq/demo/springboot/netty/server/handler/DemoStrongNettyServerHandler.java
package com.ljq.demo.springboot.netty.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 强化版 netty 服务端事务处理器
 * @Author: junqiang.lu
 * @Date: 2023/8/23
 */
@Slf4j
@Component
// 标记该类实例可以被多个 channel 共享
@ChannelHandler.Sharable
public class DemoStrongNettyServerHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 工作线程池
     */
    private final ExecutorService executorService = new ThreadPoolExecutor(4, 8, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(10000), new DefaultThreadFactory("strong-netty-work-pool"),
            new ThreadPoolExecutor.CallerRunsPolicy());


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        // 打印接收到的消息(观察 netty work 线程)
        log.info("strong netty server received message: {}", s);
        executorService.execute(() -> {
            // 异步处理业务(观察线程池线程)
            log.info("consume message async: {}", s);
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                log.error("work thread sleep error.", e);
            }
        });
    }
}

2.4 Netty 客户端 Handler

客户端的 Handler 就不需要添加线程池了,客户端主要是发送多,接收少

demo-netty-server/src/main/java/com/ljq/demo/springboot/netty/server/handler/DemoStrongNettyClientHandler.java
package com.ljq.demo.springboot.netty.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Description: 强化版 netty 客户端事务处理器
 * @Author: junqiang.lu
 * @Date: 2023/8/23
 */
@Slf4j
@Component
// 标记该类实例可以被多个 channel 共享
@ChannelHandler.Sharable
public class DemoStrongNettyClientHandler extends SimpleChannelInboundHandler<String> {


    /**
     * 接收消息
     *
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        log.info("strong netty client receive server message: {}", s);
    }

    /**
     * 通道激活,创建连接
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("strong netty client connect to server.");
    }
}

3 推荐参考资料

Netty如何解决粘包半包问题

4 Github 源码

Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo/tree/master/demo-netty-server

个人公众号:404Code,分享半个互联网人的技术与思考,感兴趣的可以关注.
404Code

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值