RSocket vs WebSocket:Spring Boot 3.3 中的兩大實時通信利器
隨著現(xiàn)代互聯(lián)網(wǎng)應(yīng)用的不斷發(fā)展,實時通信已經(jīng)成為許多應(yīng)用程序不可或缺的功能。無論是社交網(wǎng)絡(luò)、在線游戲還是數(shù)據(jù)監(jiān)控系統(tǒng),實時通信都能提供快速、無縫的信息交換。而實現(xiàn)實時通信的兩種主要協(xié)議是 RSocket 和 WebSocket。
RSocket 是一種新的、先進(jìn)的應(yīng)用層協(xié)議,旨在提供高效的網(wǎng)絡(luò)通信。與傳統(tǒng)的請求/響應(yīng)模式不同,RSocket 支持請求-響應(yīng)、請求-流、流-流等多種模式,從而在微服務(wù)和流式數(shù)據(jù)傳輸中表現(xiàn)得更加靈活和高效。RSocket 的優(yōu)勢在于它可以在 TCP、WebSocket 等多種傳輸協(xié)議上運行,支持背壓機(jī)制和多路復(fù)用,從而避免了資源的浪費,并保證了消息傳遞的可靠性。
WebSocket 是一種標(biāo)準(zhǔn)協(xié)議,允許客戶端和服務(wù)器之間建立持久連接,客戶端和服務(wù)器都可以主動發(fā)送消息。相較于傳統(tǒng)的 HTTP 請求-響應(yīng)模型,WebSocket 是全雙工通信,即服務(wù)器可以實時向客戶端推送數(shù)據(jù),而不需要等待客戶端發(fā)起請求,尤其適合實時數(shù)據(jù)更新場景。WebSocket 的使用場景廣泛,涵蓋了即時通訊、實時數(shù)據(jù)展示和多人在線游戲等。
運行效果:
圖片
若想獲取項目完整代碼以及其他文章的項目源碼,且在代碼編寫時遇到問題需要咨詢交流,歡迎加入下方的知識星球。
本文將結(jié)合 Spring Boot 3.3,詳細(xì)講解如何使用 RSocket 和 WebSocket 實現(xiàn)實時通信。我們將通過一個完整的示例,展示前后端交互、消息傳遞和雙向通信的實際應(yīng)用。文章還將結(jié)合具體的代碼示例,演示如何從前端向后端發(fā)送消息,并在點擊按鈕時與服務(wù)器進(jìn)行交互。
項目配置
項目依賴配置(pom.xml)
在 pom.xml 中引入 RSocket、WebSocket 以及其他必要的依賴。
<?xml versinotallow="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.icoderoad</groupId>
<artifactId>rsocket-websocket-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rsocket-websocket-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency><!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- RSocket 支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-rsocket</artifactId>
</dependency>
<!-- WebSocket 支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- Thymeleaf 模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Lombok 支持 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
應(yīng)用配置(application.yml)
server:
port: 8080
spring:
rsocket:
server:
port: 7000
transport: websocket
mapping-path: /rsocket
websocket:
enabled: true
mapping: /ws
app:
rsocket-message: "這是來自 RSocket 的消息"
websocket-message: "這是來自 WebSocket 的消息"
讀取配置類 (RSocket 和 WebSocket 配置類)
我們使用 @ConfigurationProperties 注解讀取配置文件中的 app 節(jié)點。這里使用 Lombok 來簡化實體類的代碼實現(xiàn)。
package com.icoderoad.rwebsocket.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String rsocketMessage;
private String websocketMessage;
}
RSocket 服務(wù)端實現(xiàn)
RSocket 提供了靈活的通信模型,允許服務(wù)端和客戶端以流的方式交換數(shù)據(jù)。我們通過 @MessageMapping 來定義接收和處理客戶端消息的方法。
package com.icoderoad.rwebsocket.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.stereotype.Controller;
import com.icoderoad.rwebsocket.config.AppProperties;
import reactor.core.publisher.Mono;
@Controller
public class RSocketController {
@Autowired
private AppProperties appProperties;
@MessageMapping("rsocket.message")
public Mono<String> sendMessage(String input) {
return Mono.just("RSocket服務(wù)端響應(yīng): " + input + " | " + appProperties.getRsocketMessage());
}
}
WebSocket 服務(wù)端實現(xiàn)
WebSocket 服務(wù)端使用 Spring 提供的 TextWebSocketHandler 來處理消息。我們在收到客戶端消息后,通過會話對象將響應(yīng)發(fā)送回客戶端。
package com.icoderoad.rwebsocket.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.icoderoad.rwebsocket.config.AppProperties;
@Controller
public class WebSocketController extends TextWebSocketHandler {
@Autowired
private AppProperties appProperties;
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String clientMessage = message.getPayload();
String responseMessage = "WebSocket服務(wù)端響應(yīng): " + clientMessage + " | " + appProperties.getWebsocketMessage();
session.sendMessage(new TextMessage(responseMessage));
}
}
WebSocket 配置類
使用 WebSocketConfigurer 來注冊 WebSocket 的處理器,并允許跨域訪問。
package com.icoderoad.rwebsocket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import com.icoderoad.rwebsocket.controller.WebSocketController;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
private final WebSocketController webSocketController;
public WebSocketConfig(WebSocketController webSocketController) {
this.webSocketController = webSocketController;
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(webSocketController, "/ws")
.setAllowedOrigins("*");
}
}
前端實現(xiàn)
前端使用 Thymeleaf 渲染,并通過 jQuery 與后端的 RSocket 和 WebSocket 進(jìn)行交互。用戶可以輸入消息,通過點擊按鈕發(fā)送到后端,并接收后端的響應(yīng)。
在 src/main/resources/templates 目錄下創(chuàng)建 index.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RSocket & WebSocket Demo</title>
<!-- 引入 Bootstrap 樣式 -->
<link rel="stylesheet">
<!-- 引入 jQuery 和 Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- 引入 RSocket 庫 -->
<script src="/js/rsocket-core.min.js"></script>
<script src="/js/rsocket-websocket-client.min.js"></script>
<style>
.message-box {
max-height: 300px;
overflow-y: auto;
border: 1px solid #dee2e6;
padding: 10px;
border-radius: 0.25rem;
background-color: #f8f9fa;
}
.message-box p {
margin-bottom: 0.5rem;
}
</style>
</head>
<body>
<div class="container">
<h1 class="mt-5">RSocket & WebSocket Demo</h1>
<!-- WebSocket 區(qū)域 -->
<div class="mt-5">
<h3>WebSocket 消息</h3>
<div class="input-group mb-3">
<input type="text" id="websocket-input" class="form-control" placeholder="輸入 WebSocket 消息">
<button id="send-websocket" class="btn btn-primary">發(fā)送 WebSocket 消息</button>
</div>
<div id="websocket-messages" class="message-box"></div>
</div>
<!-- RSocket 區(qū)域 -->
<div class="mt-5">
<h3>RSocket 消息</h3>
<div class="input-group mb-3">
<input type="text" id="rsocket-input" class="form-control" placeholder="輸入 RSocket 消息">
<button id="send-rsocket" class="btn btn-success">發(fā)送 RSocket 消息</button>
</div>
<div id="rsocket-messages" class="message-box"></div>
</div>
</div>
<script>
$(document).ready(function () {
// WebSocket 連接
const ws = new WebSocket("ws://localhost:8080/ws");
ws.onmessage = function (event) {
$("#websocket-messages").append(`<p>${event.data}</p>`);
};
// 發(fā)送 WebSocket 消息
$("#send-websocket").click(function () {
const message = $("#websocket-input").val();
if (message.trim()) {
ws.send(message);
$("#websocket-input").val('');
}
});
const { RSocketClient } = window['rsocket-core'];
const { default: RSocketWebSocketClient } = window['rsocket-websocket-client'];
// RSocket 客戶端創(chuàng)建和連接
async function createRSocketClient() {
const transportOptions = {
url: 'ws://localhost:7001/rsocket',
};
const setupOptions = {
keepAlive: 60000,
lifetime: 180000,
dataMimeType: 'application/json',
metadataMimeType: 'message/x.rsocket.routing.v0',
};
const transport = new RSocketWebSocketClient(transportOptions);
const client = new RSocketClient({
setup: setupOptions,
transport
});
try {
return await client.connect();
} catch (error) {
console.error("RSocket 連接錯誤: ", error);
throw error;
}
}
// 處理 RSocket 消息
async function setupRSocket() {
try {
const socket = await createRSocketClient();
$("#send-rsocket").click(function () {
const message = $("#rsocket-input").val();
if (message.trim()) {
socket.requestResponse({
data: message,
metadata: String.fromCharCode('rsocket.message'.length) + 'rsocket.message'
}).subscribe({
onComplete: (response) => {
$("#rsocket-messages").append(`<p>${response.data}</p>`);
$("#rsocket-input").val('');
},
onError: (error) => {
console.error("RSocket 錯誤: ", error);
}
});
}
});
} catch (error) {
console.error("啟動 RSocket 客戶端失敗: ", error);
}
}
setupRSocket();
});
</script>
</body>
</html>
總結(jié)
通過結(jié)合 RSocket 和 WebSocket,我們可以在 Spring Boot 3.3 中輕松實現(xiàn)高效的實時通信。RSocket 通過其多種通信模型和背壓機(jī)制,為流式數(shù)據(jù)傳輸提供了強(qiáng)大的支持;WebSocket 則在全雙工實時通信方面表現(xiàn)出色,適合需要即時數(shù)據(jù)更新的場景。通過本文的實例,讀者可以在項目中靈活應(yīng)用這兩種技術(shù),實現(xiàn)高效的消息交互。在前端,我們使用簡單的輸入框和按鈕,演示了如何與服務(wù)器進(jìn)行消息通信。這種方式不僅提升了用戶體驗,還能大幅提高系統(tǒng)的響應(yīng)速度和處理效率。