SpringBoot 集成 Netty 使用WebSocket功能,并实现token校验

SpringBoot 集成 Netty 使用Socket功能,并实现token校验

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

import cn.hutool.core.util.ObjectUtil;
import com.netty.config.MyWebSocketServerProtocolHandler;
import com.netty.config.NettyWebSocketHandler;
import com.netty.config.NettyWebSocketParamHandler;
import io.netty.bootstrap.ServerBootstrap;
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.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

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

    private final NettyWebSocketParamHandler nettyWebSocketParamHandler;

    private final NettyWebSocketHandler nettyWebSocketHandler;

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;

    public NettyBooster(NettyWebSocketParamHandler nettyWebSocketParamHandler, NettyWebSocketHandler nettyWebSocketHandler) {
        this.nettyWebSocketParamHandler = nettyWebSocketParamHandler;
        this.nettyWebSocketHandler = nettyWebSocketHandler;
    }

    @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 HttpServerCodec(),
                                        // http 消息聚合器  512*1024为接收的最大content-length
                                        new HttpObjectAggregator(8192),
                                        // 支持异步发送大的码流(大的文件传输),但不占用过多的内存,防止java内存溢出
                                        new ChunkedWriteHandler(),
                                        //设置一个空闲状态处理程序(心跳机制),读空闲,写空闲,读写空闲
                                        new IdleStateHandler(20, 0, 0),
                                        // 自定义参数处理器,必须放在 new WebSocketServerProtocolHandler() 处理器之前
                                        nettyWebSocketParamHandler,
                                        // websocket支持,前端通过访问IP:端口/web-socket连接,设置路由(这里使用了自己继承WebSocketServerProtocolHandler重写了decode方法的类,目的是为了获取到客户端传递的自定义Close Code)
                                        new MyWebSocketServerProtocolHandler("/web-socket"),
                                        //自定义处理程序
                                        nettyWebSocketHandler
                                );
                            }
                        });
        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. 编写URL参数处理程序
package com.netty;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.URLUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * URL参数处理程序,这时候连接还是个http请求,没有升级成webSocket协议,此处SimpleChannelInboundHandler泛型使用FullHttpRequest
 *
 * @author Nanase Takeshi
 * @date 2022/5/7 15:07
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyWebSocketParamHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    /**
     * 此处进行url参数提取,重定向URL,访问webSocket的url不支持带参数的,带参数会抛异常,这里先提取参数,将参数放入通道中传递下去,重新设置一个不带参数的url
     *
     * @param ctx     the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *                belongs to
     * @param request the message to handle
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        String uri = request.uri();
        log.info("NettyWebSocketParamHandler.channelRead0 --> : 格式化URL... {}", uri);
        Map<CharSequence, CharSequence> queryMap = UrlBuilder.ofHttp(uri).getQuery().getQueryMap();
        //将参数放入通道中传递下去
        AttributeKey<String> attributeKey = AttributeKey.valueOf("token");
        ctx.channel().attr(attributeKey).setIfAbsent(queryMap.get("token").toString());
        request.setUri(URLUtil.getPath(uri));
        ctx.fireChannelRead(request.retain());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("NettyWebSocketParamHandler.exceptionCaught --> cause: ", cause);
        ctx.close();
    }

}
  1. 对客户端传递的数据进行拦截提取自定义code,放入通道中传递下去
package com.ljky.ambl.config;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import java.util.List;

/**
 * 继承WebSocketServerProtocolHandler,自定义处理下客户端发送的自定义关闭消息
 *
 * @author Nanase Takeshi
 * @date 2022/6/2 11:40
 */
public class MyWebSocketServerProtocolHandler extends WebSocketServerProtocolHandler {

    public MyWebSocketServerProtocolHandler(String websocketPath) {
        super(websocketPath);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
    	//对客户端消息解码时如果消息是关闭通道类型,则获取Close Code
        if (frame instanceof CloseWebSocketFrame) {
            CloseWebSocketFrame closeWebSocketFrame = (CloseWebSocketFrame) frame;
            //传递CloseWebSocketFrame的statusCode
            AttributeKey<Integer> attributeKey = AttributeKey.valueOf("closeCode");
            ctx.channel().attr(attributeKey).setIfAbsent(closeWebSocketFrame.statusCode());
        }
        super.decode(ctx, frame, out);
    }

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

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 自定义WebSocket处理程序
 * SimpleChannelInboundHandler的泛型需要传递WebSocketFrame
 *
 * @author Nanase Takeshi
 * @date 2022/5/7 15:07
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyWebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    /**
     * 事件回调
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            //协议握手成功完成
            log.info("NettyWebSocketHandler.userEventTriggered --> : 协议握手成功完成");
            //检查用户token
            AttributeKey<String> attributeKey = AttributeKey.valueOf("token");
            //从通道中获取用户token
            String token = ctx.channel().attr(attributeKey).get();
            //校验token逻辑
            //......
            if(1 == 2) {
                //如果token校验不通过,发送连接关闭的消息给客户端,设置自定义code和msg用来区分下服务器是因为token不对才导致关闭
                ctx.writeAndFlush(new CloseWebSocketFrame(400, "token 无效")).addListener(ChannelFutureListener.CLOSE);
            }
        }
        //通过判断IdleStateEvent的状态来实现自己的读空闲,写空闲,读写空闲处理逻辑
        if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
            //读空闲,关闭通道
            log.info("NettyWebSocketHandler.userEventTriggered --> : 读空闲,关闭通道");
            ctx.close();
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame textWebSocketFrame) throws Exception {
        log.info("NettyWebSocketHandler.channelRead0 --> : 发消息来了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyWebSocketHandler.channelInactive --> : 通道关闭了");
        //获取用户关闭通道时设置的close code
        AttributeKey<Integer> attributeKey = AttributeKey.valueOf("closeCode");
        Attribute<Integer> closeCode = ctx.channel().attr(attributeKey);
        //对closeCode进行区分处理....
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("NettyWebSocketHandler.exceptionCaught --> cause: ", cause);
        ctx.close();
    }

}

你可能感兴趣的:(netty,java,spring,boot,websocket,后端)