模擬一個廣播彈幕的websocket。gateway經過eureka註冊中心拉取服務進行轉發websocketjavascript
<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>
spring:
application:
name: bullet
server:
port: 5678
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1025/eureka/
@SpringBootApplication
public class BulletApplication {
public static void main(String[] args) {
SpringApplication.run(BulletApplication.class, args);
}
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketAutoConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/bullet") //開啓/bullet端點
.setAllowedOrigins("*") //容許跨域訪問
.withSockJS(); //使用sockJS
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/toAll"); //訂閱Broker名稱
}
}
使用lombok的@Getter和@Setter註解來自動生成get、set方法css
@Getter
@Setter
public class BulletMessageVO {
String username;
String message;
}
@Controller
public 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;
}
}
<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>
spring:
application:
name: gateway
gateway:
routes:
- id: bulletscreen
# 重點!/info必須使用http進行轉發,lb表明從註冊中心獲取服務
uri: lb://bullet
predicates:
# 重點!轉發該路徑!
- Path=/bullet/info/**
- id: bulletscreen
# 重點!lb:ws://表明從註冊中心獲取服務,而且轉發協議爲websocket,這種格式懷疑人生!
uri: lb:ws://bullet
predicates:
# 轉發/bullet端點下的全部路徑
- Path=/bullet/**
server:
port: 8888
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1025/eureka/
@SpringCloudApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
這個是從網上找來的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>
開啓多個html頁面,並打開控制檯
java
在多個頁面中點擊鏈接按鈕,觀察控制檯是否鏈接成功
jquery
https://github.com/naah69/SpringCloud-Gateway-WebSocket-Demogit