溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springboot項目如何接入websocket

發布時間:2021-05-11 15:02:10 來源:億速云 閱讀:326 作者:小新 欄目:開發技術

這篇文章將為大家詳細講解有關springboot項目如何接入websocket,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

springboot是什么

springboot一種全新的編程規范,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程,SpringBoot也是一個服務于框架的框架,服務范圍是簡化配置文件。


最近一個項目又重啟了,之前支付了要手動點擊已付款,所以這次想把這個不友好體驗干掉。另外以后的掃碼登錄什么的都需要這個服務支持。之前掃碼登錄這塊用的mqtt,時間上是直接把mqtt的連接信息返回給前端。前端連接mqtt服務,消費信息。這次不想這樣弄了,準備接入websocket。

一、環境說明

我這里是springBoot2.4.5 + springCloud2020.1.2,這里先從springBoot對接開始,逐步再增加深度,不過可能時間不夠,就簡單接入能滿足現在業務場景就stop。沒辦法,從入職就開始的一個項目到現在,要死不活的,沒有客戶就不投入,有客戶就催命,真不知道還能堅持多久。。。。。。

二、引包

<!-- websocket支持 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

現在springboot對接websocket就值需要這么簡單的一個包了。

三、配置類

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * websocket配置類
 *
 * @author zhengwen
 **/
@Slf4j
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

就這一個,里面的bean是用來掃描Endpoint注解的類的。
配置文件都沒什么好說的,簡單對接用不上,也不用什么調優。

四、websocketServer

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.concurrent.ConcurrentHashMap;


/**
 * @author zhengwen
 **/
@Slf4j
@Component
@ServerEndpoint("/wsPushMessage/{wsUserId}")
public class MyWebSocketSever {
    /**
     * 靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的線程安全Set,用來存放每個客戶端對應的WebSocket對象。
     */
    private static ConcurrentHashMap<String, MyWebSocketSever> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 與某個客戶端的連接會話,需要通過它來給客戶端發送數據
     */
    private Session session;
    /**
     * 接收wsUserId
     */
    private String wsUserId = "";

    /**
     * 連接建立成
     * 功調用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("wsUserId") String userId) {
        this.session = session;
        this.wsUserId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //加入set中
            webSocketMap.put(userId, this);
        } else {
            //加入set中
            webSocketMap.put(userId, this);
            //在線數加1
            addOnlineCount();
        }
        log.info("用戶連接:" + userId + ",當前在線人數為:" + getOnlineCount());
        sendMessage("連接成功");
    }

    /**
     * 連接關閉
     * 調用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(wsUserId)) {
            webSocketMap.remove(wsUserId);
            //從set中刪除
            subOnlineCount();
        }
        log.info("用戶退出:" + wsUserId + ",當前在線人數為:" + getOnlineCount());
    }

    /**
     * 收到客戶端消
     * 息后調用的方法
     *
     * @param message 客戶端發送過來的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用戶消息:" + wsUserId + ",報文:" + message);
        //可以群發消息
        //消息保存到數據庫、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                //解析發送的報文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加發送人(防止串改)
                jsonObject.put("fromUserId", this.wsUserId);
                String toUserId = jsonObject.getString("toUserId");
                //傳送給對應toUserId用戶的websocket
                if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
                    webSocketMap.get(toUserId).sendMessage(message);
                } else {
                    //否則不在這個服務器上,發送到mysql或者redis
                    log.error("請求的userId:" + toUserId + "不在該服務器上");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用戶錯誤:" + this.wsUserId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

}

核心方法就這么幾個,這里面的細節可以自行根據業務場景處理,比如給信息增加一個類型,然后搞個公用方法,根據信息類型走不同業務邏輯,存庫等等都可以的。

五、前端測試js

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通訊</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    let socket;
    function openSocket() {

        const socketUrl = "ws://localhost:8810/wsPushMessage/" + $("#userId").val();
        console.log(socketUrl);
        if(socket!=null){
            socket.close();
            socket=null;
        }
        socket = new WebSocket(socketUrl);
        //打開事件
        socket.onopen = function() {
            console.log("websocket已打開");
        };
        //獲得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //發現消息進入,開始處理前端觸發邏輯
        };
        //關閉事件
        socket.onclose = function() {
            console.log("websocket已關閉");
        };
        //發生了錯誤事件
        socket.onerror = function() {
            console.log("websocket發生了錯誤");
        }
    }
    function sendMessage() {

        socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
        console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
    }
	function closeSocket(){
		socket.close();
	}
</script>
<body>
<p>【socket開啟者的ID信息】:<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【客戶端向服務器發送的內容】:<div><input id="toUserId" name="toUserId" type="text" value="20">
    <input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【開啟連接】:<div><a onclick="openSocket()">開啟socket</a></div>
<p>【發送信息】:<div><a onclick="sendMessage()">發送消息</a></div>
<p>【關閉連接】:<div><a onclick="closeSocket()">關閉socket</a></div>
</body>

</html>

六、測試效果

springboot項目如何接入websocket

關于“springboot項目如何接入websocket”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女