終于實(shí)現(xiàn)了 SpringBoot+WebSocket實(shí)時(shí)監(jiān)控異常....
閱讀本文大概需要 4.5?分鐘。
來自:cnblogs.com/jae-tech/p/15409340.html

<html><head><meta charset="utf-8" /><title>實(shí)時(shí)監(jiān)控title>head><style>.item {display: flex;border-bottom: 1px solid #000000;justify-content: space-between;width: 30%;line-height: 50px;height: 50px;}.item span:nth-child(2){margin-right: 10px;margin-top: 15px;width: 20px;height: 20px;border-radius: 50%;background: #55ff00;}.nowI{background: #ff0000 ;}style><body><div id="app"><div v-for="item in list" class="item"><span>{{item.id}}.{{item.name}}span><span :class='item.state==-1?"nowI":""'>span>div>div>body><script src="./js/vue.min.js">script><script type="text/javascript">var vm = new Vue({el: "#app",data: {list: [{id: 1,name: '張三',state: 1},{id: 2,name: '李四',state: 1},{id: 3,name: '王五',state: 1},{id: 4,name: '韓梅梅',state: 1},{id: 5,name: '李磊',state: 1},]}})var webSocket = null;if ('WebSocket' in window) {//創(chuàng)建WebSocket對(duì)象webSocket = new WebSocket("ws://localhost:18801/webSocket/" + getUUID());//連接成功webSocket.onopen = function() {console.log("已連接");webSocket.send("消息發(fā)送測(cè)試")}//接收到消息webSocket.onmessage = function(msg) {//處理消息var serverMsg = msg.data;var t_id = parseInt(serverMsg) //服務(wù)端發(fā)過來的消息,ID,string需轉(zhuǎn)化為int類型才能比較for (var i = 0; i < vm.list.length; i++) {var item = vm.list[i];if(item.id == t_id){item.state = -1;vm.list.splice(i,1,item)break;}}};//關(guān)閉事件webSocket.onclose = function() {console.log("websocket已關(guān)閉");};//發(fā)生了錯(cuò)誤事件webSocket.onerror = function() {console.log("websocket發(fā)生了錯(cuò)誤");}} else {alert("很遺憾,您的瀏覽器不支持WebSocket!")}function getUUID() { //獲取唯一的UUIDreturn 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random() * 16 | 0,v = c == 'x' ? r : (r & 0x3 | 0x8);return v.toString(16);});}script>html>


#端口server:port: 18801#密碼,因?yàn)榻涌诓恍枰獧?quán)限,所以加了個(gè)密碼做校驗(yàn)mySocket:myPwd: jae_123
@Configurationpublic class WebSocketConfig {/*** 注入一個(gè)ServerEndpointExporter,該Bean會(huì)自動(dòng)注冊(cè)使用@ServerEndpoint注解申明的websocket endpoint*/public ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}}
/*** @author jae* @ServerEndpoint("/webSocket/{uid}") 前端通過此URI與后端建立鏈接*/("/webSocket/{uid}")@Componentpublic class WebSocketServer {private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);//靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。private static final AtomicInteger onlineNum = new AtomicInteger(0);//concurrent包的線程安全Set,用來存放每個(gè)客戶端對(duì)應(yīng)的WebSocketServer對(duì)象。private static CopyOnWriteArraySetsessionPools = new CopyOnWriteArraySet (); /*** 有客戶端連接成功*/public void onOpen(Session session, @PathParam(value = "uid") String uid){sessionPools.add(session);onlineNum.incrementAndGet();log.info(uid + "加入webSocket!當(dāng)前人數(shù)為" + onlineNum);}/*** 連接關(guān)閉調(diào)用的方法*/public void onClose(Session session) {sessionPools.remove(session);int cnt = onlineNum.decrementAndGet();log.info("有連接關(guān)閉,當(dāng)前連接數(shù)為:{}", cnt);}/*** 發(fā)送消息*/public void sendMessage(Session session, String message) throws IOException {if(session != null){synchronized (session) {session.getBasicRemote().sendText(message);}}}/*** 群發(fā)消息*/public void broadCastInfo(String message) throws IOException {for (Session session : sessionPools) {if(session.isOpen()){sendMessage(session, message);}}}/*** 發(fā)生錯(cuò)誤*/public void onError(Session session, Throwable throwable){log.error("發(fā)生錯(cuò)誤");throwable.printStackTrace();}}
@RestController@RequestMapping()public class WebSocketController {public String myPwd;private WebSocketServer webSocketServer;/*** 手機(jī)客戶端請(qǐng)求接口* @param id 發(fā)生異常的設(shè)備ID* @param pwd 密碼(實(shí)際開發(fā)記得加密)* @throws IOException*/public void onReceive(String id,String pwd) throws IOException {if(pwd.equals(myPwd)){ //密碼校驗(yàn)一致(這里舉例,實(shí)際開發(fā)還要有個(gè)密碼加密的校驗(yàn)的),則進(jìn)行群發(fā)webSocketServer.broadCastInfo(id);}}}




推薦閱讀:
SpringBoot多線程環(huán)境下,解決多個(gè)定時(shí)器沖突問題
內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊(duì)列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper、數(shù)據(jù)結(jié)構(gòu)、限流熔斷降級(jí)......等技術(shù)棧!
?戳閱讀原文領(lǐng)取!? ? ? ? ? ? ? ??? ??? ? ? ? ? ? ? ? ? ?朕已閱?
評(píng)論
圖片
表情

