vue、springboot
實(shí)現(xiàn)場景
點(diǎn)擊同步之后更新數(shù)據(jù),更新時(shí)間比較長,因此使用異步,之后該按鈕置灰,在數(shù)據(jù)更新完成之后,服務(wù)端通知客戶端已經(jīng)同步成功,通知提示框,用戶即可查看數(shù)據(jù)
前端
1、在對(duì)應(yīng)的頁面編寫初始化、連接成功,錯(cuò)誤,接受信息方法
// 初始化方法
init() {
//1、websocket接口的url
let ws =
"http://localhost:21204/ws/platofrmAsync/" +
this.$store.state.user.userId;
// 實(shí)例化socket
this.socket = new WebSocket(ws);
// 監(jiān)聽socket連接
this.socket.onopen = this.socketopen;
// 監(jiān)聽socket錯(cuò)誤信息
this.socket.onerror = this.error;
// 監(jiān)聽socket消息
this.socket.onmessage = this.getMessage;
// 監(jiān)聽socket斷開連接的消息
this.socket.close = this.close;
},
// 連接成功方法
socketopen() {
console.log("socket連接成功");
},
// 連接錯(cuò)誤
error() {
console.log("連接錯(cuò)誤");
},
// 接受信息接口
getMessage(message) {
console.log("收到消息");
//當(dāng)接受到信息之后,就可以做后續(xù)的處理了
let data = JSON.parse(message.data);
this.$notify({
title: "消息通知",
type: "success",
message: "平臺(tái)【" + data.platformName + "】已經(jīng)資源樹同步完成",
position: "bottom-right",
});
this.getList();
},
// 關(guān)閉處理
close() {
console.log("連接關(guān)閉");
},
2、mounted或者created方法中啟動(dòng)初始化方法
mounted() {
this.init();
},
后端
1、配置ServerEndpointExporter
package com.eshore.framework.config.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* 這個(gè)Bean的作用是自動(dòng)注冊(cè)使用了@ServerEndpoint注解的Bean
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
2、編寫ServerEndpoint
package com.eshore.web.websocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* author:walker
* time: 2023/6/28
* description: 平臺(tái)同步
*/
@Component
@Slf4j
// 類似于controlelr 服務(wù)點(diǎn)
@ServerEndpoint(value = "/ws/platofrmAsync/{userId}")
public class PlatformAsyncWebSocket {
// 用來存儲(chǔ)每一個(gè)客戶端對(duì)象對(duì)應(yīng)的WsController對(duì)象
private static Map<String, PlatformAsyncWebSocket> onlineUsers = new ConcurrentHashMap<>();
// 聲明Session對(duì)象,通過該對(duì)象可以給指定的用戶發(fā)送請(qǐng)求
private Session session;
/**
* 連接建立時(shí)被調(diào)用
*/
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
log.info("連接成功");
// 將局部的session對(duì)象賦值給成員session對(duì)象
this.session = session;
// 這里是因?yàn)榍岸嗽趥鲾?shù)據(jù)的時(shí)候,會(huì)將userId傳過來
//所以使用將userId和websocket對(duì)象存儲(chǔ)起來,方便下次服務(wù)端推送信息的時(shí)候使用
Map<String, List<String>> requestParameterMap = this.session.getRequestParameterMap();
List<String> userIds = requestParameterMap.get("userId");
String userId = userIds.get(0);
onlineUsers.put(userId, this);
}
/**
* 接收到客戶端消息時(shí)被調(diào)用
*/
@OnMessage
public void onMessage(String message, Session session) {
}
/**
* 連接被關(guān)閉時(shí)調(diào)用
*/
@OnClose
public void onClose(Session session) {
//關(guān)閉時(shí)則將map中的用戶移除
Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
List<String> userIds = requestParameterMap.get("userId");
String userId = userIds.get(0);
onlineUsers.remove(userId);
}
//推送消息
//將消息推送給某個(gè)指定的用戶
public void sendMsg(String userId, String message) {
try {
PlatformAsyncWebSocket wsController = onlineUsers.get(userId);
wsController.session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("用戶{} 發(fā)送信息{}失敗", userId, message);
e.printStackTrace();
}
}
}
3、編寫測試服務(wù)端推送方法
package com.eshore.web.controller.test;
import com.alibaba.fastjson.JSON;
import com.eshore.biz.domain.BizPlatformInfo;
import com.eshore.web.websocket.PlatformAsyncWebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class WebsocketTest {
@Autowired
private PlatformAsyncWebSocket platformAsyncWebSocket;
@GetMapping("/send/{userId}")
public void testWsSend(@PathVariable(value = "userId") String userId){
BizPlatformInfo bizPlatformInfo = new BizPlatformInfo();
bizPlatformInfo.setId(1L);
bizPlatformInfo.setPlatformName("平臺(tái)AA");
platformAsyncWebSocket.sendMsg(userId, JSON.toJSONString(bizPlatformInfo));
}
}
測試
1、首先前端進(jìn)入對(duì)應(yīng)的頁面,就會(huì)出現(xiàn)連接成功文章來源:http://www.zghlxwxcb.cn/news/detail-514977.html
2、調(diào)用測試方法
之后就可以看到 通知成功的信息了文章來源地址http://www.zghlxwxcb.cn/news/detail-514977.html
到了這里,關(guān)于vue+springboot+websocket實(shí)現(xiàn)消息通知,含應(yīng)用場景的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!