在Spring Cloud中使用WebSocket可以通过以下步骤实现:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
}
@Controller
public class WebSocketController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // 模拟处理时间
return new Greeting("Hello, " + message.getName() + "!");
}
}
public class HelloMessage {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Greeting {
private String content;
public Greeting(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Spring WebSocket Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/webjars/sockjs-client/1.5.1/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/2.3.4/stomp.min.js"></script>
<script>
var stompClient = null;
function connect() {
var socket = new SockJS('/websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
function sendName() {
var name = $("#name").val();
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
</script>
</head>
<body>
<div>
<label for="name">Name:</label>
<input type="text" id="name" />
<button onclick="sendName()">Send</button>
</div>
<div>
<table id="greetings">
<tr>
<th>Greetings</th>
</tr>
</table>
</div>
<script>
connect();
</script>
</body>
</html>
以上步骤完成后,就可以在Spring Cloud中使用WebSocket了。通过访问前端页面,输入名称并点击发送按钮,页面将会显示收到的问候消息。在后台,greeting()
方法将接收到的消息进行处理,并将处理结果发送到/topic/greetings
频道,前端页面通过订阅该频道来接收消息并展示在页面上。
推荐的腾讯云相关产品:腾讯云WebSocket服务(https://cloud.tencent.com/product/wss)
领取专属 10元无门槛券
手把手带您无忧上云