springboot+sockjs进行消息推送(广播模式)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                springboot+sockjs进行消息推送(广播模式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                第一步:引入pom依賴:
<!-- sockjs --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><!-- 進行頁面跳轉 --><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*//*** 注冊端點,發布或者訂閱消息的時候需要連接此端點* setAllowedOrigins 非必須,*表示允許其他域進行連接* withSockJS 表示開始sockejs支持*/@Configuration //注解開啟使用STOMP協議來傳輸基于代理(message broker)的消息,這時控制器支持使用@MessageMapping,就像使用@RequestMapping一樣 @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{@Override//注冊STOMP協議的節點(endpoint),并映射指定的urlpublic void registerStompEndpoints(StompEndpointRegistry registry) {//注冊一個STOMP的endpoint,并指定使用SockJS協議registry.addEndpoint("/endpoint-websocket").setAllowedOrigins("*").withSockJS();}//配置消息代理(Message Broker)/*** 配置消息代理(中介)* enableSimpleBroker 服務端推送給客戶端的路徑前綴* setApplicationDestinationPrefixes 客戶端發送數據給服務器端的一個前綴*/@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {//點對點應配置一個/user消息代理,廣播式應配置一個/topic消息代理registry.enableSimpleBroker("/topic","/user");//點對點使用的訂閱前綴(客戶端訂閱路徑上會體現出來),不設置的話,默認也是/user/registry.setUserDestinationPrefix("/user");} }?第三步:后臺java代碼
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 = 10000)public void sendTopicMessage() {System.out.println("后臺廣播正在推送中...");User user=new User();user.setName("qushen");user.setAge(10);this.template.convertAndSend("/topic/getResponse",user);}}1.SimpMessagingTemplate:SpringBoot提供操作WebSocket的對象?
2.@Scheduled(fixedRate = 10000):是每十秒執行一次,記得去主類上用@EnableScheduling開啟一下定時任務。
3.template.convertAndSend:直接向前端推送消息。
第四步:編寫前臺代碼
<!DOCTYPE html> <html><head><title>websocket.html</title> <meta name="content-type" content="text/html" charset="UTF-8"></head> <body><div> <p id="name"></p> <p id="age"></p></div><!-- 獨立JS --><script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.slim.js"></script><script type="text/javascript" src="js/topic.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>第五步:編寫?topic.js
var stompClient = null; //加載完瀏覽器后 調用connect(),打開雙通道$(function(){ //打開雙通道connect()})//強制關閉瀏覽器 調用websocket.close(),進行正常關閉window.onunload = function() {disconnect()}function connect(){var socket = new SockJS('/endpoint-websocket'); //連接SockJS的endpoint名稱為"endpointOyzc"stompClient = Stomp.over(socket);//使用STMOP子協議的WebSocket客戶端stompClient.connect({},function(frame){//連接WebSocket服務端 console.log('Connected:' + frame);//通過stompClient.subscribe訂閱/topic/getResponse 目標(destination)發送的消息stompClient.subscribe('/topic/getResponse',function(response){showResponse(JSON.parse(response.body));});});}//關閉雙通道function disconnect(){if(stompClient != null) {stompClient.disconnect();}console.log("Disconnected");}function showResponse(message){var response = $("#name");var response = $("#age");response.append("<p>"+message.name+"</p>");response.append("<p>"+message.age+"</p>");}最后訪問瀏覽器:http://localhost:8080/index,每十秒便可以得到如下圖所示:
?
總結
以上是生活随笔為你收集整理的springboot+sockjs进行消息推送(广播模式)的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 磨题帮怎么把试题导入(磨题帮导入遗漏了答
 - 下一篇: 颂怎么读(颖怎么读)