springboot 实现服务端推送消息之websocket netty

2021/4/25 10:27:18

本文主要是介绍springboot 实现服务端推送消息之websocket netty,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文章目录

  • 前言
  • 一、实现思路
  • 二、关键代码
    • 1.相关maven
    • 2.NettyServer
    • 3.WebSocketHandler
    • 4.NettyConfig
    • 5.HearBeatHandler
    • 6.实现类调用触发消息推送
    • 7.前端实现
    • 8.nginx代理websocket及访问路径


前言

前篇我们提到用sse实现服务端推送消息,但是发现sse每次推送后SseEmitter都有有一个短暂的时间处于complete状态,导致快速连续的发送消息会导致 ResponseBodyEmitter is already set complete错误,所以改为websocket服务端推送消息。如有sse相关解决方案欢迎讨论。


一、实现思路

1、NettyServer通过通信通道自定义的handler 添加websocket
2、WebSocketHandler 继承SimpleChannelInboundHandler重写部分方法实现自身逻辑
3、NettyConfig 保存通信通道的Map,用于保存通信对象id
4、HearBeatHandler 对websocket进行心跳监测(websocket默认长时间无通信会自动关闭通道,通常做法可以前端轮询向服务端发送消息,也可以后端服务器自己进行心跳监控,定时发送信息保持连接状态)


二、关键代码

1.相关maven

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.63.Final</version>
</dependency>
<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.1</version>
    <scope>provided</scope>
</dependency>

2.NettyServer

import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import java.net.InetSocketAddress;

@Component
public class NettyServer{

    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
    /**
     * webSocket协议名
     */
    private static final String WEBSOCKET_PROTOCOL = "webSocket";

    /**
     * 端口号默认58080
     */
    @Value("${webSocket.netty.port:58080}")
    private int port;

    /**
     * webSocket路径默认/ws
     */
    @Value("${webSocket.netty.path:/ws}")
    private String webSocketPath;

    @Autowired
    private WebSocketHandler webSocketHandler;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;

    /**
     * 启动
     * @throws InterruptedException
     */
    private void start() throws InterruptedException {
        bossGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        // bossGroup辅助客户端的tcp连接请求, workGroup负责与客户端之前的读写操作
        bootstrap.group(bossGroup,workGroup);
        // 设置NIO类型的channel
        bootstrap.channel(NioServerSocketChannel.class);
        // 设置监听端口
        bootstrap.localAddress(new InetSocketAddress(port));
        // 连接到达时会创建一个通道
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // 流水线管理通道中的处理程序(Handler),用来处理业务
                // webSocket协议本身是基于http协议的,所以这边也要使用http编解码器
                ch.pipeline().addLast(new HttpServerCodec());
                ch.pipeline().addLast(new ObjectEncoder());
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
                ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                // 以块的方式来写的处理器
                ch.pipeline().addLast(new ChunkedWriteHandler());
                /*
                说明:
                1、http数据在传输过程中是分段的,HttpObjectAggregator可以将多个段聚合
                2、这就是为什么,当浏览器发送大量数据时,就会发送多次http请求
                 */
                ch.pipeline().addLast(new HttpObjectAggregator(8192));
                /*
                说明:
                1、对应webSocket,它的数据是以帧(frame)的形式传递
                2、浏览器请求时 ws://localhost:58080/xxx 表示请求的uri
                3、核心功能是将http协议升级为ws协议,保持长连接
                */
                ch.pipeline().addLast(new WebSocketServerProtocolHandler(webSocketPath, WEBSOCKET_PROTOCOL, true, 65536 * 10));

                // 添加Netty空闲超时检查的支持
                // 1. 读空闲超时(超过一定的时间会发送对应的事件消息)
                // 2. 写空闲超时
                // 3. 读写空闲超时
                ch.pipeline().addLast(new IdleStateHandler(30, 30, 30));
                //添加心跳处理
                ch.pipeline().addLast(new HearBeatHandler());
                // 自定义的handler,处理业务逻辑
                ch.pipeline().addLast(webSocketHandler);

            }
        });
        // 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功
        ChannelFuture channelFuture = bootstrap.bind(port).sync();
        log.info("netty server - 启动成功:{}",channelFuture.channel().localAddress());
        // 对关闭通道进行监听
        //channelFuture.channel().closeFuture().sync();
    }

    /**
     * 释放资源
     * @throws InterruptedException
     */
    @PreDestroy
    public void destroy() throws InterruptedException {
        if(bossGroup != null){
            bossGroup.shutdownGracefully().sync();
        }
        if(workGroup != null){
            workGroup.shutdownGracefully().sync();
        }
    }

    @PostConstruct()
    public void init() {
        //需要开启一个新的线程来执行netty server 服务器
        new Thread(() -> {
            try {
                start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

3.WebSocketHandler

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * TextWebSocketFrame类型, 表示一个文本帧
 * @author Mr.wanter
 * @date 2021-04-19 16:30:16
 */
@Component
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);

    /**
     * 一旦连接,第一个被执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerAdded 被调用"+ctx.channel().id().asLongText());
        // 添加到channelGroup 通道组
        NettyConfig.getChannelGroup().add(ctx.channel());
    }

    /**
     * 读取数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("服务器收到消息:{}",msg.text());

        // 获取用户ID,关联channel
        JSONObject jsonObject = JSONObject.parseObject(msg.text());
        String uid = jsonObject.getString("uid");
        NettyConfig.getUserChannelMap().put(uid,ctx.channel());

        // 将用户ID作为自定义属性加入到channel中,方便随时channel中获取用户ID
        AttributeKey<String> key = AttributeKey.valueOf("userId");
        ctx.channel().attr(key).setIfAbsent(uid);

        // 回复消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame("success"));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerRemoved 被调用"+ctx.channel().id().asLongText());
        // 删除通道
        NettyConfig.getChannelGroup().remove(ctx.channel());
        removeUserId(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("异常:{}",cause.getMessage());
        // 删除通道
        NettyConfig.getChannelGroup().remove(ctx.channel());
        removeUserId(ctx);
        ctx.close();
    }

    /**
     * 删除用户与channel的对应关系
     * @param ctx
     */
    private void removeUserId(ChannelHandlerContext ctx){
        AttributeKey<String> key = AttributeKey.valueOf("userId");
        String userId = ctx.channel().attr(key).get();
        NettyConfig.getUserChannelMap().remove(userId);
    }
}


4.NettyConfig

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 保存通道对象.
 *
 * @author: Mr.wanter
 * @since 2021-04-19 16:28
 */
public class NettyConfig {
    /**
     * 定义一个channel组,管理所有的channel
     * GlobalEventExecutor.INSTANCE 是全局的事件执行器,是一个单例
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 存放用户与Chanel的对应信息,用于给指定用户发送消息
     */
    private static ConcurrentHashMap<String,Channel> userChannelMap = new ConcurrentHashMap<>();

    private NettyConfig() {}

    /**
     * 获取channel组
     * @return
     */
    public static ChannelGroup getChannelGroup() {
        return channelGroup;
    }

    /**
     * 获取用户channel map
     * @return
     */
    public static ConcurrentHashMap<String,Channel> getUserChannelMap(){
        return userChannelMap;
    }
}

5.HearBeatHandler

如果不添加可采用前端轮询的方式定时向服务端发送数据。

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 心跳监测.
 *
 * @author: Mr.wanter
 * @since 2021-04-19 18:01
 */
public class HearBeatHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(HearBeatHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent)evt;

            if(idleStateEvent.state() == IdleState.READER_IDLE) {
                //log.info("读空闲事件触发...");
                ctx.channel().writeAndFlush(new TextWebSocketFrame("success"));
            }
            else if(idleStateEvent.state() == IdleState.WRITER_IDLE) {
                //log.info("写空闲事件触发...");
                ctx.channel().writeAndFlush(new TextWebSocketFrame("success"));
            }
            else if(idleStateEvent.state() == IdleState.ALL_IDLE) {
                //log.info("读写空闲事件触发");
                ctx.channel().writeAndFlush(new TextWebSocketFrame("success"));
                //System.out.println("关闭通道资源");
                //ctx.channel().close();
            }
        }
    }
}

6.实现类调用触发消息推送

该接口为接收实时消息接口,相关设备会实时推送预警数据。当数据推送保存后,通过NettyConfig.getChannelGroup().writeAndFlush(Object var1)来触发ws发送信息。

    @Override
    public String strangerEventRcv(StrangerAlarmInDTO alarmDTO) {
        //陌生人闯入数据解析入库
        AlarmPO po = new AlarmPO();
        Arrays.stream(alarmDTO.getParams().getEvents()).forEach(e -> {
            po.setName(e.getSrcName());
            po.setAlarmType(e.getEventType().toString());
            po.setHappenTime(e.getHappenTime());
            po.setUrl(e.getData().getFaceRecognitionResult().getSnap().getFaceUrl());
            alarmDao.save(po);
            //ws发送消息
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            NettyConfig.getChannelGroup()
                     .writeAndFlush(new TextWebSocketFrame(JSONObject.fromObject(AlarmTipDTO.builder()
                     .name(po.getName()).alarmType("1")
                     .happenTime(formatter.format(po.getHappenTime())).build()).toString()));
        });

        //返回指定内容
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("code", "0");
        jsonObject.addProperty("msg", "success");
        jsonObject.addProperty("data", "");
        return jsonObject.toString();
    }

7.前端实现

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script>
  var socket;
  // 判断当前浏览器是否支持webSocket
  if(window.WebSocket){
    socket = new WebSocket("ws://localhost:58080/ws")
    // 相当于channel的read事件,ev 收到服务器回送的消息
    socket.onmessage = function (ev) {
      var rt = document.getElementById("responseText");
	  if(ev.data!="success"){
		rt.value = rt.value + "\n" + ev.data;
	  }
    }
    // 相当于连接开启
    socket.onopen = function (ev) {
      var rt = document.getElementById("responseText");
      rt.value = "连接开启了..."
      socket.send(
        JSON.stringify({
          // 连接成功将,用户ID传给服务端
          uid: "123456"
        })
      );
    }
    // 相当于连接关闭
    socket.onclose = function (ev) {
      var rt = document.getElementById("responseText");
      rt.value = rt.value + "\n" + "连接关闭了...";
    }
  }else{
    alert("当前浏览器不支持webSocket")
  }


</script>
  <form onsubmit="return false">
    <textarea id="responseText" style="height: 150px; width: 300px;"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
  </form>
</body>
</html>

8.nginx代理websocket及访问路径

#ws
location /websocket/ {
   proxy_pass  http://localhost:58080/;
   proxy_read_timeout 120s;

   proxy_set_header Host $host;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
}

访问路径:例nginx ip为123.12.1.3 端口为8092 则前端访问路径为

 socket = new WebSocket("ws://123.12.1.3:8092/websocket/ws")


这篇关于springboot 实现服务端推送消息之websocket netty的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程