當前位置:
首頁 > 知識 > springboot websocket後台主動推送消息

springboot websocket後台主動推送消息

springboot,websocket,後台主動推送消息

1.pom

[html] view plain copy

  1. <?xml

    version="1.0" encoding="UTF-8"

    ?>

  2. <project

    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"

    >

  4. <modelVersion>

    4.0.0

    </modelVersion>

  5. <groupId>

    com.liuxl.cartmall

    </groupId>

  6. <artifactId>

    spring-websocket

    </artifactId>

  7. <version>

    0.0.1-SNAPSHOT

    </version>

  8. <packaging>

    jar

    </packaging>

  9. <name>

    spring-websocket

    </name>

  10. <description>

    Demo project for Spring Boot
  11. https://spring.io/guides/gs/messaging-stomp-websocket/

    </description>

  12. <parent>

  13. <groupId>

    org.springframework.boot

    </groupId>

  14. <artifactId>

    spring-boot-starter-parent

    </artifactId>

  15. <version>

    2.0.2.RELEASE

    </version>

  16. <relativePath/>

    <!-- lookup parent from repository -->
  17. </parent>

  18. <properties>

  19. <project.build.sourceEncoding>

    UTF-8

    </project.build.sourceEncoding>

  20. <project.reporting.outputEncoding>

    UTF-8

    </project.reporting.outputEncoding>

  21. <java.version>

    1.8

    </java.version>

  22. </properties>

  23. <dependencies>

  24. <dependency>

  25. <groupId>

    org.springframework.boot

    </groupId>

  26. <artifactId>

    spring-boot-starter-websocket

    </artifactId>

  27. </dependency>

  28. <dependency>

  29. <groupId>

    org.webjars

    </groupId>

  30. <artifactId>

    webjars-locator-core

    </artifactId>

  31. </dependency>

  32. <dependency>

  33. <groupId>

    org.webjars

    </groupId>

  34. <artifactId>

    sockjs-client

    </artifactId>

  35. <version>

    1.0.2

    </version>

  36. </dependency>

  37. <dependency>

  38. <groupId>

    org.webjars

    </groupId>

  39. <artifactId>

    stomp-websocket

    </artifactId>

  40. <version>

    2.3.3

    </version>

  41. </dependency>

  42. <dependency>

  43. <groupId>

    org.webjars

    </groupId>

  44. <artifactId>

    bootstrap

    </artifactId>

  45. <version>

    3.3.7

    </version>

  46. </dependency>

  47. <dependency>

  48. <groupId>

    org.webjars

    </groupId>

  49. <artifactId>

    jquery

    </artifactId>

  50. <version>

    3.1.0

    </version>

  51. </dependency>

  52. <dependency>

  53. <groupId>

    org.springframework.boot

    </groupId>

  54. <artifactId>

    spring-boot-starter-test

    </artifactId>

  55. <scope>

    test

    </scope>

  56. </dependency>

  57. </dependencies>

  58. <build>

  59. <plugins>

  60. <plugin>

  61. <groupId>

    org.springframework.boot

    </groupId>

  62. <artifactId>

    spring-boot-maven-plugin

    </artifactId>

  63. </plugin>

  64. </plugins>

  65. </build>

  66. </project>

2.SpringWebsocketApplication springboot 啟動類

[csharp] view plain copy

  1. package com.liuxl.cartmall;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public

    class

    SpringWebsocketApplication {
  6. public

    static

    void

    main(String[] args) {
  7. SpringApplication.run(SpringWebsocketApplication.

    class

    , args);
  8. }
  9. }

3.WebSocketConfig

[java] view plain copy

  1. package

    com.liuxl.cartmall.websocket;
  2. import

    org.springframework.context.annotation.Configuration;
  3. import

    org.springframework.messaging.simp.config.MessageBrokerRegistry;
  4. import

    org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
  5. import

    org.springframework.web.socket.config.annotation.StompEndpointRegistry;
  6. import

    org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
  7. //@EnableWebSocketMessageBroker註解表示開啟使用STOMP協議來傳輸基於代理的消息,Broker就是代理的意思。
  8. @Configuration
  9. @EnableWebSocketMessageBroker
  10. public

    class

    WebSocketConfig

    implements

    WebSocketMessageBrokerConfigurer {
  11. @Override
  12. public

    void

    configureMessageBroker(MessageBrokerRegistry registry) {
  13. // 訂閱Broker名稱
  14. registry.enableSimpleBroker("/topic");
  15. // 全局使用的消息前綴(客戶端訂閱路徑上會體現出來)
  16. registry.setApplicationDestinationPrefixes("/app");
  17. // 點對點使用的訂閱前綴(客戶端訂閱路徑上會體現出來),不設置的話,默認也是/user/
  18. // registry.setUserDestinationPrefix("/user/");
  19. }
  20. // registerStompEndpoints方法表示註冊STOMP協議的節點,並指定映射的URL。
  21. @Override
  22. public

    void

    registerStompEndpoints(StompEndpointRegistry registry) {
  23. // 這一行代碼用來註冊STOMP協議節點,同時指定使用SockJS協議。
  24. registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS();
  25. }
  26. }

4.Greeting,HelloMessage

[java] view plain copy

  1. package

    com.liuxl.cartmall.websocket;
  2. public

    class

    Greeting {
  3. private

    String content;
  4. public

    Greeting() {
  5. }
  6. public

    Greeting(String content) {
  7. this

    .content = content;
  8. }
  9. public

    String getContent() {
  10. return

    content;
  11. }
  12. }

[java] view plain copy

  1. package

    com.liuxl.cartmall.websocket;
  2. public

    class

    HelloMessage {
  3. private

    String name;
  4. public

    HelloMessage() {
  5. }
  6. public

    HelloMessage(String name) {
  7. this

    .name = name;
  8. }
  9. public

    String getName() {
  10. return

    name;
  11. }
  12. public

    void

    setName(String name) {
  13. this

    .name = name;
  14. }
  15. }

5.GreetingController

[java] view plain copy

  1. package

    com.liuxl.cartmall.websocket;
  2. import

    org.slf4j.Logger;
  3. import

    org.slf4j.LoggerFactory;
  4. import

    org.springframework.beans.factory.annotation.Autowired;
  5. import

    org.springframework.messaging.handler.annotation.MessageMapping;
  6. import

    org.springframework.messaging.handler.annotation.SendTo;
  7. import

    org.springframework.messaging.simp.SimpMessagingTemplate;
  8. import

    org.springframework.stereotype.Controller;
  9. import

    org.springframework.web.bind.annotation.RequestMapping;
  10. import

    org.springframework.web.bind.annotation.ResponseBody;
  11. import

    org.springframework.web.util.HtmlUtils;
  12. @Controller
  13. public

    class

    GreetingController {
  14. private

    Logger logger = LoggerFactory.getLogger(

    this

    .getClass());
  15. @Autowired
  16. private

    SimpMessagingTemplate messagingTemplate;
  17. // @MessageMapping註解和我們之前使用的@RequestMapping類似
  18. // @SendTo註解表示當伺服器有消息需要推送的時候,會對訂閱了@SendTo中路徑的瀏覽器發送消息。
  19. @MessageMapping("/hello")
  20. @SendTo("/topic/greetings")
  21. public

    Greeting greeting(HelloMessage message)

    throws

    Exception {
  22. Thread.sleep(1000); // simulated delay
  23. return

    new

    Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
  24. }
  25. @RequestMapping("/send")
  26. @ResponseBody
  27. public

    void

    send(){
  28. templateTest();
  29. }
  30. //客戶端只要訂閱了/topic/subscribeTest主題,調用這個方法即可
  31. public

    void

    templateTest() {
  32. messagingTemplate.convertAndSend("/topic/greetings",

    new

    Greeting("伺服器主動推的數據"));
  33. }
  34. }

6.後台 messagingTemplate.convertAndSend("/topic/greetings", new Greeting("伺服器主動推的數據")); 就可以實現主動推送到前台了

7.index.js

[javascript] view plain copy

  1. var

    stompClient =

    null

    ;
  2. /**
  3. * 建立webshocket連接
  4. */
  5. function

    connect() {
  6. // 建立連接對象(還未發起連接)
  7. var

    socket =

    new

    SockJS("/gs-guide-websocket");
  8. // 獲取 STOMP 子協議的客戶端對象
  9. stompClient = Stomp.over(socket);
  10. // 向伺服器發起websocket連接並發送CONNECT幀
  11. stompClient.connect({},

    function

    (frame) {
  12. // 連接成功時(伺服器響應 CONNECTED 幀)的回調方法
  13. // setConnected(true);
  14. console.log("Connected: " + frame);
  15. stompClient.subscribe("/topic/greetings",

    function

    (greeting) {
  16. showGreeting(JSON.parse(greeting.body).content);
  17. });
  18. },

    function

    errorCallBack(error) {
  19. // 連接失敗時(伺服器響應 ERROR 幀)的回調方法
  20. });
  21. }
  22. function

    showGreeting(content) {
  23. $("#daiban_count").text(content);
  24. }
  25. $(

    function

    () {
  26. // 監聽信息
  27. connect();
  28. });

7.需要源碼,去git下載,下載地址是:spring-websocket

springboot websocket後台主動推送消息

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

json與protobuf的速度之爭

TAG:程序員小新人學習 |