springboot+sockjs进行消息推送(一对一模式)
生活随笔
收集整理的這篇文章主要介紹了
springboot+sockjs进行消息推送(一对一模式)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
第一步:引入pom依賴:
<!-- sockjs --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><!-- 進行頁面跳轉(zhuǎn) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>第二步:編寫sockjs的springboot配置文件
import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry;/*** 配置WebSocket*//*** 注冊端點,發(fā)布或者訂閱消息的時候需要連接此端點* setAllowedOrigins 非必須,*表示允許其他域進行連接* withSockJS 表示開始sockejs支持*/@Configuration //注解開啟使用STOMP協(xié)議來傳輸基于代理(message broker)的消息,這時控制器支持使用@MessageMapping,就像使用@RequestMapping一樣 @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{@Override//注冊STOMP協(xié)議的節(jié)點(endpoint),并映射指定的urlpublic void registerStompEndpoints(StompEndpointRegistry registry) {//注冊一個STOMP的endpoint,并指定使用SockJS協(xié)議registry.addEndpoint("/endpoint-websocket").setAllowedOrigins("*").withSockJS();}//配置消息代理(Message Broker)/*** 配置消息代理(中介)* enableSimpleBroker 服務端推送給客戶端的路徑前綴* setApplicationDestinationPrefixes 客戶端發(fā)送數(shù)據(jù)給服務器端的一個前綴*/@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {//點對點應配置一個/user消息代理,廣播式應配置一個/topic消息代理registry.enableSimpleBroker("/topic","/user");//點對點使用的訂閱前綴(客戶端訂閱路徑上會體現(xiàn)出來),不設置的話,默認也是/user/registry.setUserDestinationPrefix("/user");} }?第三步:后臺java代碼?
package com.baidu.websocket.controller;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;import com.baidu.websocket.model.InMessage; import com.baidu.websocket.model.OutMessage; import com.baidu.websocket.model.User;@Controller public class GameInfoController {@RequestMapping("/index")public String index() {return "index";}@Autowiredprivate SimpMessagingTemplate template;//一對一隊列推送消息@Scheduled(fixedRate = 5000)public void sendQueueMessage() {System.out.println("后臺一對一推送!");User user=new User();user.setId(1);user.setName("qushedn");user.setAge(10);this.template.convertAndSendToUser(user.getId()+"","/queue/getResponse",user);}}1.SimpMessagingTemplate:SpringBoot提供操作WebSocket的對象?
2.@Scheduled(fixedRate = 5000):是每五秒執(zhí)行一次,記得去主類上用@EnableScheduling開啟一下定時任務。
3.template.convertAndSend:直接向前端推送消息。里面用逗號隔開的三個參數(shù)分別是:
A:發(fā)送給誰
B:發(fā)送的url
C:發(fā)送的內(nèi)容
第四步:編寫前臺代碼
<!DOCTYPE html> <html><head><title>websocket.html</title> <meta name="content-type" content="text/html" charset="UTF-8"></head> <body><div> <p id="id"></p> </div><!-- 獨立JS --><script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.slim.js"></script><script type="text/javascript" src="js/queue.js" charset="utf-8"></script><script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script><script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script></body> </html>第五步:編寫?queue.js?
var stompClient = null; //加載完瀏覽器后 調(diào)用connect(),打開雙通道$(function(){ //打開雙通道connect()}) //強制關閉瀏覽器 調(diào)用websocket.close(),進行正常關閉window.onunload = function() {disconnect()}function connect(){var Id=1;var socket = new SockJS('/endpoint-websocket'); //連接SockJS的endpoint名稱為"endpointOyzc"stompClient = Stomp.over(socket);//使用STMOP子協(xié)議的WebSocket客戶端stompClient.connect({},function(frame){//連接WebSocket服務端 console.log('Connected:' + frame);stompClient.subscribe("/user/"+Id+"/queue/getResponse",function(response){//stompClient.subscribe('/topic/getResponse',function(response){var code=JSON.parse(response.body); showResponse(code) });});}//關閉雙通道function disconnect(){if(stompClient != null) {stompClient.disconnect();}console.log("Disconnected");}function showResponse(message){var response = $("#name");response.append("<p>只有userID為"+message.id+"的人才能收到</p>");}?最后訪問瀏覽器:http://localhost:8080/index,每五秒便可以得到如下圖所示:
?
總結
以上是生活随笔為你收集整理的springboot+sockjs进行消息推送(一对一模式)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 颂怎么读(颖怎么读)
- 下一篇: 路由器该怎么选-家庭如何选择路由器