在Vue3和Spring Boot中实现WebSocket进行后端主动前端推送数据及时通讯的示例代码如下:
后端(Spring Boot):
- 添加依赖(在pom.xml中):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 配置WebSocket (WebSocketConfig.java):
@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("/ws").withSockJS();
}
}
- 创建WebSocket服务 (WebSocketService.java):
@Service
public class WebSocketService {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
public void sendMessageToClient(String destination, String message) {
simpMessagingTemplate.convertAndSend(destination, message);
}
}
前端(Vue3):
- 安装依赖:
npm install vue-socket.io-extended
- 设置WebSocket连接并监听消息 (main.js):
import { createApp } from 'vue'
import App from './App.vue'
import { Socket } from 'vue-socket-io-extended'
const app = createApp(App)
const socket = app.use(Socket, {
connection: 'ws://localhost:8080/ws',
// 可以添加额外的传递给socket.io的选项
})
app.mount('#app')
- 在组件中发送和接收消息 (Notification.vue):
<template>
<div>
<!-- 显示接收到的消息 -->
<div v-for="message in messages" :key="message">{{ message }}</div>
</div>
</template>
<script>
export default {
data() {
return {
messages: []
}
},
mounted() {
// 监听服务端推送的消息
this.$socket.on('message', (data) => {
this.messages.push(data)
})
},
methods: {
// 发送消息到服务端
sendMessage(message) {
this.$socket.emit('message', message)
}
}
}
</script>
后端发送消息:
当你需要从后端发送消息到前端时,可以在任何需要的地方调用WebSocketService
中的sendMessageToClient
方法。
@RestController
public class SomeController {
@Autowired
private WebSocketService webSocketService;
@GetMapping("/sendMessage")
public void sendMessage() {
String message = "Hello, this is a message from server!";
webSocketService.sendMessageToClient("/topic/publ