spring 整合netty 实例,解决分包和粘包

springboot 整合netty5

文章目录

  • springboot 整合netty5
      • 1 导包
      • 2 配置
      • 3 实现
      • 3测试

1 导包


     
        
            io.netty
            netty-all
            5.0.0.Alpha1
        



2 配置

netty:
  port: 81


3 实现

package com.liu.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
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.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
@Slf4j
public class NettyServer {

    /**
     * boss 线程组用于处理连接工作
     */
    private EventLoopGroup boss = new NioEventLoopGroup();
    /**
     * work 线程组用于数据处理
     */
    private EventLoopGroup work = new NioEventLoopGroup();

    @Autowired
    private ServerColletHandler serverColletHandler;


    @Value("${netty.port}")
    private Integer port;

    @PostConstruct
    public void start(){

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss,work)
                .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                // 这里使用的是自定义分隔符作为 ,防止 数据粘包问题 分包
                ByteBuf delimiter = Unpooled.copiedBuffer(">###".getBytes());
                channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024*1024,delimiter));
                channel.pipeline().addLast(new StringDecoder());
                channel.pipeline().addLast(new StringEncoder());
                channel.pipeline().addLast(serverColletHandler);
            }
        });
        bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的设置,链接缓冲池的大小
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的设置,维持链接的活跃,清除死链接
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的设置,关闭延迟发送
  
        //绑定端口
        ChannelFuture future = bootstrap.bind(port);
       if(future.isSuccess()){
           System.out.println("netty server is  started !!!");
       }
    }

    @PreDestroy
    public void destory() throws InterruptedException {
        boss.shutdownGracefully().sync();
        work.shutdownGracefully().sync();
        log.info("关闭Netty");
    }

}



3测试

数据包的接收和发送

spring 整合netty 实例,解决分包和粘包_第1张图片

你可能感兴趣的:(netty,springboot)