模擬一個廣播彈幕的websocket。gateway通過eureka注冊中心拉取服務進行轉發websocket
1.搭建 Spring WebSocket
1.1 pom.xml websocket maven依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency>
1.2 application.yml 配置文件
spring:application:name: bulletserver:port: 5678eureka:client:serviceUrl:defaultZone: http://localhost:1025/eureka/
1.3 BulletApplication websocket啟動程序
@SpringBootApplicationpublic class BulletApplication {public static void main(String[] args) {SpringApplication.run(BulletApplication.class, args);}}
1.4 WebSocketAutoConfig websocket配置類
@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketAutoConfig implements WebSocketMessageBrokerConfigurer {@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {registry.addEndpoint("/bullet") //開啟/bullet端點.setAllowedOrigins("*") //允許跨域訪問.withSockJS(); //使用sockJS}@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {registry.enableSimpleBroker("/toAll"); //訂閱Broker名稱}}
1.5 BulletMessageVO類
使用lombok的@Getter和@Setter注解來自動生成get、set方法
@Getter@Setterpublic class BulletMessageVO {String username;String message;}
1.6 BulletController websocket控制器
@Controllerpublic class BulletController {@MessageMapping("/chat")@SendTo("/toAll/bulletScreen") //SendTo 發送至 Broker 下的指定訂閱路徑public String say(BulletMessageVO clientMessage) {String result=null;if (clientMessage!=null){result=clientMessage.getUsername()+":"+clientMessage.getMessage();}return result;}}
2 搭建 Spring Cloud Gateway
2.1 pom.xml gateway網關maven依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope></dependency>
2.2 application.yml gateway網關配置文件
spring:application:name: gatewaygateway:routes:- id: bulletscreen# 重點!/info必須使用http進行轉發,lb代表從注冊中心獲取服務uri: lb://bulletpredicates:# 重點!轉發該路徑!- Path=/bullet/info/**- id: bulletscreen# 重點!lb:ws://代表從注冊中心獲取服務,並且轉發協議為websocket,這種格式懷疑人生!uri: lb:ws://bulletpredicates:# 轉發/bullet端點下的所有路徑- Path=/bullet/**server:port: 8888eureka:client:serviceUrl:defaultZone: http://localhost:1025/eureka/
2.3 GatewayApplication gateway啟動類
@SpringCloudApplicationpublic class GatewayApplication {public static void main(String[] args) {SpringApplication.run(GatewayApplication.class, args);}}
3 編寫html
這個是從網上找來的html代碼,可以保存到本地文件,不需要放入服務里面
<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>Spring Boot WebSocket+廣播式</title></head><body onload="disconnect()"><noscript><h2 style="color:#ff0000">貌似你的瀏覽器不支持websocket</h2></noscript><div><div><button id="connect" onclick="connect()">連接</button><button id="disconnect" onclick="disconnect();">斷開連接</button></div><div id="conversationDiv"><label>輸入你的名字</label> <input type="text" id="name" /><br><label>輸入消息</label> <input type="text" id="messgae" /><button id="send" onclick="send();">發送</button><p id="response"></p></div></div><script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script><script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script><script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><script type="text/javascript">var stompClient = null;//gateway網關的地址var host="http://127.0.0.1:8888";function setConnected(connected) {document.getElementById('connect').disabled = connected;document.getElementById('disconnect').disabled = !connected;document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';$('#response').html();}function connect() {//地址+端點路徑,構建websocket鏈接地址var socket = new SockJS(host+'/bullet');stompClient = Stomp.over(socket);stompClient.connect({}, function(frame) {setConnected(true);console.log('Connected:' + frame);//監聽的路徑以及回調stompClient.subscribe('/toAll/bulletScreen', function(response) {showResponse(response.body);});});}function disconnect() {if (stompClient != null) {stompClient.disconnect();}setConnected(false);console.log("Disconnected");}function send() {var name = $('#name').val();var message = $('#messgae').val();//發送消息的路徑stompClient.send("/chat", {}, JSON.stringify({username:name,message:message}));}function showResponse(message) {var response = $('#response');response.html(message);}</script></body></html>
4 啟動程序
- 啟動Eureka 服務端,開啟注冊中心
- 啟動Bullet WebSocket程序
- 啟動GateWay網關
5 測試程序
-
開啟多個html頁面,並打開控制台

-
在多個頁面中點擊連接按鈕,觀察控制台是否連接成功

- 輸入名字和消息,觀察是否成功進行廣播

6 源碼
https://github.com/naah69/SpringCloud-Gateway-WebSocket-Demo
