03.06 Springboot下的WebSocket開發

今天遇到一個需求,需要對接第三方掃碼跳轉。一種方案是前端頁面輪詢後端服務,但是這種空輪詢會虛耗資源,實時性比較差而且也不優雅。所以決定使用另一種方案,websocket。以前就知道websocket,屬於全雙工長連接,適合實時在線聊天,瀏覽器之間的協同編輯工作,多人在線遊戲等場景。

但是一直沒機會用,今天正好可以使用一下。

Springboot下的WebSocket開發


簡單記錄一下步驟,親測可用。

  1. 引入依賴
<code>      <dependency>
          <groupid>org.springframework.boot/<groupid>
          <artifactid>spring-boot-starter-websocket/<artifactid>
      /<dependency>/<code>

springboot已經非常貼心的為我們編寫好了starter

  1. 配置config
<code>@Configuration
public class WebSocketConfig {

  @Bean
  public ServerEndpointExporter serverEndpointExporter() {
      return new ServerEndpointExporter();
  }

}/<code>

必須有這個config,把ws服務暴露出去。

  1. 編寫webSocket server
<code>@Slf4j
@Component
@ServerEndpoint("/webSocket/{id}")
public class MyWebSocket {
/**
* 靜態變量 用來記錄當前在線連接數

*/
private static int onlineCount = 0;

/**
* 服務端與單一客戶端通信 使用Map來存放 其中標識Key為id
*/
private static ConcurrentMap<string> webSocketMap = new ConcurrentHashMap<>();
//不需要區分可使用set
//private static CopyOnWriteArraySet<websockettest> webSocketSet = new CopyOnWriteArraySet<websockettest>();

public static ConcurrentMap<string> getWebSocketMap() {
return webSocketMap;
}

/**
* 與某個客戶端的連接會話 需要通過它來給客戶端發送數據
*/
private Session session;

/**
* 連接建立成功調用的方法
*
* @param session 可選的參數 session為與某個客戶端的連接會話 需要通過它來給客戶端發送數據
*/
@OnOpen
public void onOpen(Session session, @PathParam("id") String id) {
this.session = session;

webSocketMap.put(id, this);

addOnlineCount();
log.info("有新連接加入,當前在線數為" + getOnlineCount());
}

/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {

Map<string> map = session.getPathParameters();
webSocketMap.remove(Integer.parseInt(map.get("id")));

subOnlineCount();
log.info("有一連接關閉!當前在線數為" + getOnlineCount());
}

/**
* 收到客戶端消息後調用的方法
*
* @param message 客戶端發送過來的消息
* @param session 可選的參數
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("來自客戶端 " + session.getId() + " 的消息:" + message);
}

/**
* 發生錯誤時調用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("LoginResultWebSocket 發生錯誤");
error.printStackTrace();
}

/**
* 發送消息
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}

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

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

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

}/<string>/<string>/<websockettest>/<websockettest>/<string>/<code>

4.編寫測試頁面

頁面代碼就不貼了,網上很多,需要的可以看github,地址在文章最後。就是一個按鈕打開socket鏈接。一個按鈕向後端發送消息。一個用來展示從服務端收到的消息的p標籤。

Springboot下的WebSocket開發

點擊發送消息後,

Springboot下的WebSocket開發

可以看到,server端已經接收到。


然後測試頁面也可以接收到消息。我寫了一個請求,觸發一下sendMessage方法。

Springboot下的WebSocket開發

總結

websocket入門使用還是很簡單的,也很有趣。可以用來寫個在線聊天室demo。

源碼地址:

技術筆記與開源分享


分享到:


相關文章: