springboot業(yè)務(wù)功能實戰(zhàn)之告別輪詢websocket的集成使用
更新時間:2022年10月21日 11:26:41 作者:小鮑侃java
WebSocket使得客戶端和服務(wù)器之間的數(shù)據(jù)交換變得更加簡單,允許服務(wù)端主動向客戶端推送數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于springboot業(yè)務(wù)功能實戰(zhàn)之告別輪詢websocket的集成使用,需要的朋友可以參考下
后端代碼
首先加入pom文件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <!-- <version>1.3.5.RELEASE</version> --> </dependency>
加入配置類
@Configuration public class WebSocketConfig { /** * 注入ServerEndpointExporter, * 這個bean會自動注冊使用了@ServerEndpoint注解聲明的Websocket endpoint */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
加入連接發(fā)送消息方法
@Component @ServerEndpoint("/websocket/{userName}") // 此注解相當于設(shè)置訪問URL public class WebSocket { private Session session; private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>(); private static Map<String, Session> sessionPool = new HashMap<String, Session>(); private final static Logger logger = LoggerFactory.getLogger(LoginIntercept.class); @OnOpen public void onOpen(Session session, @PathParam(value = "userName") String userName) { this.session = session; webSockets.add(this); if (sessionPool.containsKey(userName)) { sessionPool.put(userName + String.valueOf(session.getId()), session); } else { sessionPool.put(userName, session); } logger.info("【websocket消息】有新的連接,總數(shù)為:" + webSockets.size()); } @OnClose public void onClose() { webSockets.remove(this); logger.info("【websocket消息】連接斷開,總數(shù)為:" + webSockets.size()); } @OnMessage public void onMessage(String message) { logger.info("【websocket消息】收到客戶端消息:" + message); } /** * 功能描述: 此為廣播消息 * * @param: [message] (消息) * @return: void () */ public void sendAllMessage(String message) { for (WebSocket webSocket : webSockets) { logger.info("【websocket消息】廣播消息:" + message); try { if (webSocket.session.isOpen()) { webSocket.session.getAsyncRemote().sendText(message); } } catch (Exception e) { e.printStackTrace(); } } } /** * 功能描述:此為單點消息 (發(fā)送文本) 現(xiàn)在可以發(fā)送給多客戶端 * * @param: [userName, message] (接收人,發(fā)送消息) * @return: void () */ public void sendTextMessage(String userName, String message) { // 遍歷sessionPool for (String key : sessionPool.keySet()) { // 存在當前用戶 if (key.toString().indexOf(userName) != -1) { Session session = sessionPool.get(key); if (session != null && session.isOpen()) { try { session.getAsyncRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } } } /** * 功能描述: 此為單點消息 (發(fā)送文本) 現(xiàn)在可以發(fā)送給多客戶端 * * @param: [userName, message] (接收人,發(fā)送消息) * @return: void () */ public void sendObjMessage(String userName, Object message) { // 遍歷sessionPool for (String key : sessionPool.keySet()) { // 存在當前用戶 if (key.toString().indexOf(userName) != -1) { Session session = sessionPool.get(key); if (session != null && session.isOpen()) { try { session.getAsyncRemote().sendObject(message); } catch (Exception e) { e.printStackTrace(); } } } } } }
發(fā)送信息
@RestController @RequestMapping("websocket") public class WebSocketController { @GetMapping("setMessage") @ApiOperation(value = "發(fā)送信息接口", notes = "發(fā)送信息接口") public Result webSocket(@ApiParam(name = "定時任務(wù)日志實體", value = "定時任務(wù)日志實體", required = false) @RequestBody MessageVO messageVO) { Result result = new Result(); String userName = messageVO.getUserName(); String message = messageVO.getMessage(); WebSocket webSocket = new WebSocket(); webSocket.sendTextMessage(userName, message); return result; } }
前段代碼
import sysConfig from "../config"; import {Notification} from 'element-ui'; import {EVENT_TYPE} from "../const"; export function openSocket(userId) { let ws = new WebSocket(`${sysConfig.SOCKET_URL}/${userId}`); // let ws = new WebSocket(`ws://121.40.165.18:8800`); ws.onopen = function (evt) { Notification({ title: '歡迎回來!', message: `${sysConfig.SOCKET_URL}/${userId}` }); }; ws.onmessage = function (e) { console.log(typeof e.data); try{ if(e.data!=undefined || e.data!=null){ let json= JSON.parse(e.data); Notification({ title: json.messageTitle, message: json.messageText }); //通知頁面更新 window.postMessage(EVENT_TYPE.updateMessage,'/'); } }catch(err){ console.log("webSocke異常,異常信息:"+err) } //ws.close(); }; ws.onclose = function (evt) { console.log('Connection closed.'); }; }
總結(jié)
到此這篇關(guān)于springboot業(yè)務(wù)功能實戰(zhàn)之告別輪詢websocket集成使用的文章就介紹到這了,更多相關(guān)springboot websocket的集成使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring源碼之事件監(jiān)聽機制詳解(@EventListener實現(xiàn)方式)
這篇文章主要介紹了Spring源碼之事件監(jiān)聽機制(@EventListener實現(xiàn)方式),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08Java 自定義Spring框架以及Spring框架的基本使用
Spring框架是由于軟件開發(fā)的復雜性而創(chuàng)建的。Spring使用的是基本的JavaBean來完成以前只可能由EJB完成的事情。然而,Spring的用途不僅僅限于服務(wù)器端的開發(fā)2021-10-10基于Ajax用戶名驗證、服務(wù)條款加載、驗證碼生成的實現(xiàn)方法
本篇文章對Ajax用戶名驗證、服務(wù)條款加載、驗證碼生成的實現(xiàn)方法,進行了詳細的分析介紹。需要的朋友參考下2013-05-05java基礎(chǔ)之Integer與int類型輸出示例解析
這篇文章主要為大家介紹了java基礎(chǔ)之Integer與int類型輸出示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06