SpringBoot使用WebSocket實現(xiàn)向前端推送消息功能
WebSocket簡介
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡協(xié)議。它實現(xiàn)了瀏覽器與服務器全雙工(full-duplex)通信——允許服務器主動發(fā)送信息給客戶端。
SpringBoot整合WebSocket的相關依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
WebSokcet工具類記錄當前的在線連接對鏈接進行操作
public class WebsocketUtil { /** * 記錄當前在線的Session */ private static final Map<String, Session> ONLINE_SESSION = new ConcurrentHashMap<>(); /** * 添加session * @param userId * @param session */ public static void addSession(String userId, Session session){ // 此處只允許一個用戶的session鏈接。一個用戶的多個連接,我們視為無效。 ONLINE_SESSION.putIfAbsent ( userId, session ); } /** * 關閉session * @param userId */ public static void removeSession(String userId){ ONLINE_SESSION.remove ( userId ); } /** * 給單個用戶推送消息 * @param session * @param message */ public static void sendMessage(Session session, String message){ if(session == null){ return; } // 同步 RemoteEndpoint.Async async = session.getAsyncRemote (); async.sendText ( message ); } /** * 向所有在線人發(fā)送消息 * @param message */ public static void sendMessageForAll(String message) { //jdk8 新方法 ONLINE_SESSION.forEach((sessionId, session) -> sendMessage(session, message)); } }
WebSocket接口處理類
/** * websocket接口處理類 */ @Component @ServerEndpoint(value = "/chat/{userId}") public class WebsocketController { /** * 連接事件,加入注解 * @param userId * @param session */ @OnOpen public void onOpen(@PathParam(value = "userId") String userId, Session session) { String message = "[" + userId + "]加入聊天室!!"; // 添加到session的映射關系中 WebsocketUtil.addSession(userId, session); // 廣播通知,某用戶上線了 // WebsocketUtil.sendMessageForAll(message); } /** * 連接事件,加入注解 * 用戶斷開鏈接 * * @param userId * @param session */ @OnClose public void onClose(@PathParam(value = "userId") String userId, Session session) { String message = "[" + userId + "]退出了聊天室..."; // 刪除映射關系 WebsocketUtil.removeSession(userId); // 廣播通知,用戶下線了 WebsocketUtil.sendMessageForAll(message); } /** * 當接收到用戶上傳的消息 * * @param userId * @param session */ @OnMessage public void onMessage(@PathParam(value = "userId") String userId, Session session, String message) { String msg = "[" + userId + "]:" + message; System.out.println("接收到信息:" + msg); // 直接廣播 WebsocketUtil.sendMessageForAll(msg); } /** * 處理用戶活連接異常 * * @param session * @param throwable */ @OnError public void onError(Session session, Throwable throwable) { try { session.close(); } catch (IOException e) { e.printStackTrace(); } throwable.printStackTrace(); } }
服務器端單個用戶推送消息
@PostMapping("/send") public void send(@RequestParam("id") String id,@RequestParam("message")String message) { Session session = ONLINE_SESSION.get(id); WebsocketUtil.sendMessage(session,message); System.out.println("發(fā)送成功"); }
使用Apifox進行測試
添加連接服務端的WebSocket接口
連接成功:
服務端推送消息
客戶端收到的消息
WebSocket工具類里面有群發(fā)的方法,大家想用可以直接調用,這里就不進行演示了
問題一:如何在上面WebSocket接口處理類中注入其他的Bean?
我也是在一次工作中遇到這樣的問題,今天正好和大家講一下如何解決
查閱資料才知道WebSocket接口處理類使用@ServerEndPoint注解表明他是一個WebSocket端點,因此Spring不會將其納入Spring容器的管理范圍,WebSocket的生命周期和Spring Bean 的生命周期并不一致,所以通過@Autowired 注解注入得到的都是空的Bean 無法使用
我們自定義一個工具類手動獲取Bean在 WebSocket接口處理類中使用:
/** *AppUtils類 * * @author qiancj * @since 2020-06-30 13:02 */ @Component("appUtils") public class AppUtils { /** * 應用上下文 */ private static ApplicationContext context; @Resource public void setApplicationContext(ApplicationContext c) { context = c; } /** * 獲取配置參數(shù) * * @param property 配置參數(shù)名 * @return 配置參數(shù)值 */ public static String getProperty(String property) { return context.getEnvironment().getProperty(property); } /** * 獲取bean對象 * * @param requiredType Class * @param <T> T * @return bean對象 */ public static <T> T getBean(Class<T> requiredType) { return context.getBean(requiredType); } /** * 獲取bean對象 * * @param name bean name * @param requiredType Class * @param <T> T * @return bean對象 */ public static <T> T getBean(String name, Class<T> requiredType) { return context.getBean(requiredType); } }
使用:
MessageService messageService = AppUtils.getBean(MessageService.class);
然后我們就可以使用messageService調用Service層相關的方法了。
問題解決。
以上就是SpringBoot使用WebSocket實現(xiàn)向前端推送消息功能的詳細內容,更多關于SpringBoot WebSocket推送消息的資料請關注腳本之家其它相關文章!
相關文章
Java編程中利用InetAddress類確定特殊IP地址的方法
這篇文章主要介紹了Java編程中利用InetAddress類確定特殊IP地址的方法,InetAddress類是Java網(wǎng)絡編程中一個相當實用的類,需要的朋友可以參考下2015-11-11Idea如何配置Maven才能優(yōu)先從本地倉庫獲取依賴(親測方法有效)
對于Idea怎么配置Maven才能優(yōu)先從本地倉庫獲取依賴,網(wǎng)上說法有很多種,都不太靠譜,最終都沒有效果,最好的解決方法是通過修改maven配置文件settings.xml,本文給大家介紹的非常詳細,需要的朋友參考下吧2023-10-10SpringBoot中集成screw(螺絲釘)實現(xiàn)數(shù)據(jù)庫表結構文檔生成方法
這篇文章主要介紹了SpringBoot中集成screw(螺絲釘)實現(xiàn)數(shù)據(jù)庫表結構文檔生成,下面以連接mysql數(shù)據(jù)庫并生成html格式的數(shù)據(jù)庫結構文檔為例,插件的使用方式除可以使用代碼外,還可以使用Maven插件的方式,需要的朋友可以參考下2024-07-07JAVA SpringBoot jar程序 Systemctl生產(chǎn)環(huán)境部署方案
這篇文章主要介紹了JAVA SpringBoot jar程序 Systemctl生產(chǎn)環(huán)境部署方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03