前言
- 前端采用:vue+sock.js+stomp.js
- 后端采用:springboot+websocket
- 项目需求:多个用户端提交报修信息,管理端web实时接收并显示。
- 实现思路:参考
我简单叙述下:后端通过轮询数据库进行监听,如何监听数据库及判断是否为新的报修信息–这部分业务代码可以参考上述链接。
本篇文章的重点有两个:
(1)前端如何建立websocket连接
(2)后端如何通过websocket的订阅模式同时通知所有订阅者有新的消息到达。
后端实现
(1)导入websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
(2)创建配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//订阅的频道
registry.enableSimpleBroker("/topic");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//提供给前端访问的socket地址
registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
}
}
(3)监听数据库,若有新消息到来,则发送给“/topic”频道,此频道接受到后再转发给订阅该频道的每一个用户。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
@Configuration
@EnableScheduling
public class ScheduleTask {
//发送消息的模板类
@Autowired
SimpMessagingTemplate simpMessagingTemplate;
//3.添加定时任务
@Scheduled(cron = "0/10 * * * * ?")
@Transactional
void configureTasks() {
System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
//监听的业务代码 已省略
if(新消息到来){
simpMessagingTemplate.convertAndSend("/topic",新消息);
}
}
}
前端实现
(1)导入sock.js和stomp.js工具类或者手动进行依赖安装
首先通过 npm 包管理工具安装两个依赖:
npm install sockjs-client
npm install stompjs
然后,按照如下方式引入:
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
如不成功,可以私我,我将两个工具类文件发给你
(2)建立websocket连接,此连接可以选择在home主页建立,因为vue是单页面应用。
//报修内容的实时更新
WebSocketMessage() {
var stomp = Stomp.over(new SockJS('/ws/ep'));
stomp.connect({},success=>{
stomp.subscribe('/topic',msg=>{
console.log("====123>>>>"+msg.body);
let recMsg = JSON.parse(msg.body);
this.$notify({
title: '成功',
message: "住户【"+recMsg.name+"】发来报修消息",
type: 'success'
});
})
},error=>{
});
},
注意:这里的地址千万不要写错,否则会一直404。
(3)最后记住需要配置动态代理。
let proxyObj = {};
//当以ws开头的url,会以ws协议进行访问,不再以http形式
proxyObj['/ws'] = {
ws: true,
//后端的根路径是/app
target: 'ws://localhost:8081/app',
};
proxyObj['/'] = {
ws: false,
target: 'http://localhost:8081/app',
changeOrigin: true,
}
module.exports = {
//禁止使用eslint
lintOnSave: false,
devServer:{
host: 'localhost',
port: 8080,
proxy: proxyObj
}
}
总结
以上就是websocket前后端代码的所有部分,如有疑问欢迎评论!