SpringBoot 集成 Netty 使用Socket功能

SpringBoot 集成 Netty 使用Socket功能

  1. 引入Netty的jar包
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.77.Final</version>
</dependency>
  1. 与Springboot集成
package com.netty;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
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;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * NettyBooter
 *
 * @author 七濑武【Nanase Takeshi】
 * @date 2022/06/23 10:14
 */
@Slf4j
@Component
public class NettyBooster {

    private final NettyServerHandler nettyServerHandler;

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;

    public NettyBooster(NettyServerHandler nettyServerHandler) {
        this.nettyServerHandler = nettyServerHandler;
    }

    @PostConstruct
    public void start() throws InterruptedException {
    	//创建BossGroup,这里指定线程数1就够了,bossGroup 就相当于领导,workerGroup 就相当于员工,领导有一个差不多了
        bossGroup = new NioEventLoopGroup(1);
        //创建WorkerGroup
        workerGroup = new NioEventLoopGroup();
        //创建服务器端的启动对象,配置参数
        ServerBootstrap serverBootstrap =
                new ServerBootstrap()
                        .group(bossGroup, workerGroup)
                        //使用NioServerSocketChannel作为服务器的通道实现
                        .channel(NioServerSocketChannel.class)
                        //设置日志处理器
                        .handler(new LoggingHandler(LogLevel.INFO))
                        //设置线程队列得到的连接个数
                        .option(ChannelOption.SO_BACKLOG, 128)
                        //设置保持活动连接的状态
                        .childOption(ChannelOption.SO_KEEPALIVE, true)
                        //给我们的workerGroup的EventLoop对应的管道设置处理器
                        .childHandler(new ChannelInitializer<SocketChannel>() {
	                        /**
	                         * 创建一个通道测试对象(匿名对象)
	                         * 给pipeline设置处理器
	                         */
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                socketChannel.pipeline().addLast(
                                		//设置一个空闲状态处理程序(心跳机制),读空闲,写空闲,读写空闲
                                        new IdleStateHandler(20, 0, 0),
                                        //一般客户端和服务端传递数据使用的JSON字符串,这里就使用String类型的编码和解码处理程序
                                        new StringDecoder()
                                        new StringEncoder(),
                                        //自定义处理程序
                                        nettyServerHandler
                                );
                            }
                        });
        serverBootstrap.bind(10000).sync();
        log.info("NettyBooster.start --> Netty 启动成功");
    }

	/**
	 * Springboot关闭时关闭Netty
	 */
    @PreDestroy
    private void destroy() throws InterruptedException {
        log.info("NettyBooster.destroy --> : 关闭 Netty...");
        if (ObjectUtil.isNotNull(bossGroup)) {
            bossGroup.shutdownGracefully().sync();
        }
        if (ObjectUtil.isNotNull(workerGroup)) {
            workerGroup.shutdownGracefully().sync();
        }
        log.info("NettyBooster.destroy --> : Netty 线程已全部关闭...");
    }

}
  1. 编写自定义处理程序
package com.netty;

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

/**
 * 说明 1.我们自定义一个Handler,需要继承Netty规定好的某个HandlerAdapter 2.这时我们自定义一个Handler,才能称为一个Handler
 *
 * @author 七濑武【Nanase Takeshi】
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 用户事件触发
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //通过判断IdleStateEvent的状态来实现自己的读空闲,写空闲,读写空闲处理逻辑
        if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
            //读空闲,关闭通道
            log.info("NettyWebSocketHandler.userEventTriggered --> : 读空闲,关闭通道");
            ctx.close();
        }
    }

    /**
     * 接受到了客户端发送的消息
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("客户端的地址:{}", ctx.channel().remoteAddress());
        log.info("客户端发送来的消息:{}", msg);
    }

    /**
     * 通道注册成功
     *
     * @param ctx
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler.handlerAdded --> 通道注册成功");
    }

    /**
     * 通道移除了
     *
     * @param ctx
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler.handlerRemoved --> 通道移除了");
    }

    /**
     * 通道开启了
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler.channelActive --> 通道开启了");
    }

    /**
     * 通道关闭了
     *
     * @param ctx
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler.channelInactive --> 通道关闭了");
    }

    /**
     * 处理异常,一般是需要关闭通道
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值