websocket实现后台向前端推送数据
springboot +websocket+vue贴入配置/*** @author zhangzhang*/@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {/*** 注册stomp端点* @param r
·
springboot +websocket+vue
贴入配置
/**
* @author zhangzhang
*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {
/**
* 注册stomp端点
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// 允许使用socketJs方式访问 即可通过http://IP:PORT/admin/ws来和服务端websocket连接
registry.addEndpoint("/admin/ws").setAllowedOrigins("*").withSockJS();
}
/**
* 配置信息代理
* @param registry
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// 订阅Broker名称 user点对点 topic广播即群发
registry.enableSimpleBroker("/user","/topic");
// 全局(客户端)使用的消息前缀
registry.setApplicationDestinationPrefixes("/app");
// 点对点使用的前缀 无需配置 默认/user
registry.setUserDestinationPrefix("/user");
}
}
后台推送数据的代码(此处为定时任务推送)
@Autowired
private SimpMessagingTemplate messagingTemplate;
@Async
@Scheduled(initialDelay = 1000,fixedRate = 5000)//启动后1秒执行没5秒执行一次
public void push() {
try {
messagingTemplate.convertAndSend("/topic/checkLogTotal", Long.valueOf(checkLogTotal==null ? "0" : checkLogTotal));
} catch (Exception e) {
e.printStackTrace();
}
}
前端vue代码
mounted() {
if ('WebSocket' in window) {
this.initWebSocket()
// this.connectSrv();
} else {
console.log('当前浏览器 Not support websocket')
}
}
initWebSocket () {
this.connection()
},
connection () {
let self = this
// 'http://**********ip:8082/admin/ws'
const socket = new SockJS('http://**********ip:8082/admin/ws')
self.stompClient = Stomp.over(socket)
self.stompClient.connect({}, (frame) => {
self.stompClient.subscribe('/topic/checkLogTotal', (greeting) => {
self.next = JSON.parse(greeting.body)
self.autoAddSumDemo()
})
})
},
更多推荐
已为社区贡献1条内容
所有评论(0)