微服务springcloud下使用websocket作消息推送几异常错误解决

Websocket实时推送消息

WebSocket是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

以前的推送技术使用 Ajax 轮询,浏览器需要不断地向服务器发送http请求来获取最新的数据,浪费很多的带宽等资源。

使用webSocket通讯,客户端和服务端只需要一次握手建立连接,就可以互相发送消息,进行数据传输,更实时地进行通讯。

一次握手建立WebSocket连接

浏览器先向服务器发送个url以ws://开头的http的GET请求,响应状态码101表示Switching Protocols切换协议,

服务器根据请求头中Upgrade:websocket把客户端的请求切换到对应的协议,即websocket协议。
微服务springcloud下使用websocket作消息推送几异常错误解决_第1张图片
响应头消息中包含Upgrade:websocket,表示它切换到的协议,即websocket协议。
微服务springcloud下使用websocket作消息推送几异常错误解决_第2张图片
响应101,握手成功,http协议切换成websocket协议了,连接建立成功,浏览器和服务器可以随时主动发送消息给对方了,并且这个连接一直持续到客户端或服务器一方主动关闭连接。
为了加深理解,用websocket实现简单的在线聊天,先画个时序图,直观感受下流程。
微服务springcloud下使用websocket作消息推送几异常错误解决_第3张图片
网上有websocket在线测试工具,可以直接使用还是挺方便的,http://www.blue-zero.com/WebSocket/

接下来进行搭建:

客户端的代码在其他地方找找你想要的效果就可以了,也可以使用在线测试,下面本人是在浏览器进行简单的连接测试的。

  1. 在微服务中使用websocket,解决向前端推送实时消息,之间遇到的问题及解决方法。
  2. 引入websocket依赖,并进行配置
<!-- webSocket 开始-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <!-- <version>1.3.5.RELEASE</version> -->
        </dependency>
<!-- webSocket 结束-->

开启WebSocket支持

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 1. 开启WebSocket支持
 2. @author : yangf
 3. @Date 2021-02-23-10:55
 **/
@Configuration
public class WebSocketConfig {
    /**
     * 扫描并注册带有@ServerEndpoint注解的所有服务端
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
  1. 创建WebSocketServer类,是websocket服务端,多例的,一次websocket连接对应一个实例,
package cn.goktech.project.handle;

import cn.goktech.daily.enums.ExceptionEnum;
import cn.goktech.project.service.MessageInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket/{userId}" ,subprotocols = {"protocol"})
@Component
public class WebSocket {

    private static MessageInfoService messageInfoService;

    @Autowired
    public void setMessageInfoService(MessageInfoService messageInfoService){
        WebSocket.messageInfoService = messageInfoService;
    }

    static Log log = LogFactory.getLog(WebSocket.class);
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
	//记录当前连接的用户
    private static List<String> userIds = new ArrayList<>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    //接收userId
    private String userId = "";


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        try {
            if("null".equals(userId) || StringUtils.isEmpty(userId)){
                sendMessageString("连接失败,为获取到用户!");
            }
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
        if(userIds.size() == ExceptionEnum.ZERO.getCode()){
            webSocketSet = new CopyOnWriteArraySet<WebSocket>();
        }
        if(userIds.contains(userId)){
            log.info("已经存在了哦--------------------》??》》》》》》》》》》");
        }else{
            userIds.add(userId);
            webSocketSet.add(this); // 加入set中
            addOnlineCount(); // 在线数加1
        }
        log.info("webSocketSet长度为:"+webSocketSet.size());
        log.info("有新窗口开始监听:" + userId + ",当前在线人数为" + getOnlineCount());
        this.userId = userId;
        try {
            //此时连接成功
            sendMessageString(”连接成功“);
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); // 从set中删除
        if(StringUtils.isNotBlank(userId)){
            userIds.remove(userId);
        }
        System.out.println("onClose-----webSocketSet:"+webSocketSet);
        if(getOnlineCount() > 0){
            subOnlineCount(); // 在线数减1
        }
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + userId + "的信息:" + message);
//群发消息
        for (WebSocket item : webSocketSet) {
            try {
                item.sendMessageString(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        System.err.println(getOnlineCount());
        try {
            this.session.getBasicRemote().sendObject(message);
        } catch (EncodeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessageString(String message) throws IOException {
        System.err.println(getOnlineCount());
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        log.info("推送消息到窗口" + userId + ",推送内容:" + message);
        System.err.println(getOnlineCount());
        for (WebSocket item : webSocketSet) {
            try {
//这里可以设定只推送给这个userId的,为null则全部推送
                if (userId == null) {
                    log.info("推送消息给全部");
                    item.sendMessageString(message);
                } else if (item.userId.equals(userId)) {
                    log.info("推送消息给"+userId);
                    item.sendMessageString(message);
                }
            } catch (IOException e) {
                System.err.println(e.getMessage());
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

    public static void sendInfoObject(String sendSocketMsg, String userId) {
        // TODO Auto-generated method stub
        log.info("推送消息到窗口" + userId + ",推送内容:" + sendSocketMsg);
        System.err.println(getOnlineCount());
        for (WebSocket item : webSocketSet) {
            try {
//这里可以设定只推送给这个userId的,为null则全部推送
                if (userId == null) {
                    log.info("推送消息给全部");
                    item.sendMessage(sendSocketMsg);
                } else if (item.userId.equals(userId)) {
                    log.info("推送消息给"+userId);
                    item.sendMessage(sendSocketMsg);
                }
            } catch (IOException e) {
                System.out.println(e.getMessage()+"------------");
                continue;
            }
        }
    }
}

@ServerEndpoint(value = "/websocket/{userId}" ,subprotocols = {"protocol"})

再需要发送信息的地方使用如下方式进行消息推送:

	try {
           WebSocket.sendInfo(”message“,userId);
        } catch (IOException e) {
            throw new BusinessException("-1","websocket向用户发送消息失败");
        }

如遇到因为gateway转发出错时可出门左转查看解决错误的方法:解决SpringCloud-Gateway转发WebSocket失败问题的过程

接下来进行连接测试及消息推送:

在这里插入图片描述
在这里插入图片描述

在浏览器 检查里面 Console 直接用WebSocket = new WebSocket("ws://localhost:8087/websocket/66");进行连接,这里66就是下面的 userId接收的参数,这里控制台监听的用户连接进来的 66。
在这里插入图片描述
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021022510104746.png微服务springcloud下使用websocket作消息推送几异常错误解决_第4张图片

上面标红的地方就是连接后下面标红的地方调用的发送方法,上面的MessageEvent为连接成功后返回的信息,data:"0",这里的0本应该是 “连接成功”,而这里截图的打印的console是我自己项目的实际返回,所以不是连接成功而是0。
微服务springcloud下使用websocket作消息推送几异常错误解决_第5张图片
到这里就已经测试成功了,需要在业务上进行消息推送的地方直接使用上面 需要发送消息。。。这里try的代码就可以推送消息给客户端了。

死鬼~看完了来个三连哦!O.O`
微服务springcloud下使用websocket作消息推送几异常错误解决_第6张图片
反手就是一个——————————奥里给

你可能感兴趣的:(Java,java,gateway,websocket)