springboot websocket後台主動推送消息
springboot,websocket,後台主動推送消息
1.pom
[html] view plain copy
<?xml
version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
<modelVersion>
4.0.0</modelVersion>
<groupId>
com.liuxl.cartmall</groupId>
<artifactId>
spring-websocket</artifactId>
<version>
0.0.1-SNAPSHOT</version>
<packaging>
jar</packaging>
<name>
spring-websocket</name>
<description>
Demo project for Spring Boot- https://spring.io/guides/gs/messaging-stomp-websocket/
</description>
<parent>
<groupId>
org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-parent
</artifactId>
<version>
2.0.2.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository --></parent>
<properties>
<project.build.sourceEncoding>
UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>
UTF-8</project.reporting.outputEncoding>
<java.version>
1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>
org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>
org.webjars</groupId>
<artifactId>
webjars-locator-core</artifactId>
</dependency>
<dependency>
<groupId>
org.webjars</groupId>
<artifactId>
sockjs-client
</artifactId>
<version>
1.0.2</version>
</dependency>
<dependency>
<groupId>
org.webjars</groupId>
<artifactId>
stomp-websocket</artifactId>
<version>
2.3.3
</version>
</dependency>
<dependency>
<groupId>
org.webjars</groupId>
<artifactId>
bootstrap</artifactId>
<version>
3.3.7</version>
</dependency>
<dependency>
<groupId>
org.webjars</groupId>
<artifactId>
jquery</artifactId>
<version>
3.1.0</version>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-test</artifactId>
<scope>
test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>
org.springframework.boot</groupId>
<artifactId>
spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.SpringWebsocketApplication springboot 啟動類
[csharp] view plain copy
- package com.liuxl.cartmall;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
public
class
SpringWebsocketApplication {public
static
void
main(String[] args) {- SpringApplication.run(SpringWebsocketApplication.
class
, args); - }
- }
3.WebSocketConfig
[java] view plain copy
package
com.liuxl.cartmall.websocket;import
org.springframework.context.annotation.Configuration;import
org.springframework.messaging.simp.config.MessageBrokerRegistry;import
org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;import
org.springframework.web.socket.config.annotation.StompEndpointRegistry;import
org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;- //@EnableWebSocketMessageBroker註解表示開啟使用STOMP協議來傳輸基於代理的消息,Broker就是代理的意思。
- @Configuration
- @EnableWebSocketMessageBroker
public
class
WebSocketConfigimplements
WebSocketMessageBrokerConfigurer {- @Override
public
void
configureMessageBroker(MessageBrokerRegistry registry) {- // 訂閱Broker名稱
- registry.enableSimpleBroker("/topic");
- // 全局使用的消息前綴(客戶端訂閱路徑上會體現出來)
- registry.setApplicationDestinationPrefixes("/app");
- // 點對點使用的訂閱前綴(客戶端訂閱路徑上會體現出來),不設置的話,默認也是/user/
- // registry.setUserDestinationPrefix("/user/");
- }
- // registerStompEndpoints方法表示註冊STOMP協議的節點,並指定映射的URL。
- @Override
public
void
registerStompEndpoints(StompEndpointRegistry registry) {- // 這一行代碼用來註冊STOMP協議節點,同時指定使用SockJS協議。
- registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS();
- }
- }
4.Greeting,HelloMessage
[java] view plain copy
package
com.liuxl.cartmall.websocket;public
class
Greeting {private
String content;public
Greeting() {- }
public
Greeting(String content) {this
.content = content;- }
public
String getContent() {return
content;- }
- }
[java] view plain copy
package
com.liuxl.cartmall.websocket;public
class
HelloMessage {private
String name;public
HelloMessage() {- }
public
HelloMessage(String name) {this
.name = name;- }
public
String getName() {return
name;- }
public
void
setName(String name) {this
.name = name;- }
- }
5.GreetingController
[java] view plain copy
package
com.liuxl.cartmall.websocket;import
org.slf4j.Logger;import
org.slf4j.LoggerFactory;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.stereotype.Controller;import
org.springframework.web.bind.annotation.RequestMapping;import
org.springframework.web.bind.annotation.ResponseBody;import
org.springframework.web.util.HtmlUtils;- @Controller
public
class
GreetingController {private
Logger logger = LoggerFactory.getLogger(this
.getClass());- @Autowired
private
SimpMessagingTemplate messagingTemplate;- // @MessageMapping註解和我們之前使用的@RequestMapping類似
- // @SendTo註解表示當伺服器有消息需要推送的時候,會對訂閱了@SendTo中路徑的瀏覽器發送消息。
- @MessageMapping("/hello")
- @SendTo("/topic/greetings")
public
Greeting greeting(HelloMessage message)throws
Exception {- Thread.sleep(1000); // simulated delay
return
new
Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");- }
- @RequestMapping("/send")
- @ResponseBody
public
void
send(){- templateTest();
- }
- //客戶端只要訂閱了/topic/subscribeTest主題,調用這個方法即可
public
void
templateTest() {- messagingTemplate.convertAndSend("/topic/greetings",
new
Greeting("伺服器主動推的數據")); - }
- }
6.後台 messagingTemplate.convertAndSend("/topic/greetings", new Greeting("伺服器主動推的數據")); 就可以實現主動推送到前台了
7.index.js
[javascript] view plain copy
var
stompClient =null
;- /**
- * 建立webshocket連接
- */
function
connect() {- // 建立連接對象(還未發起連接)
var
socket =new
SockJS("/gs-guide-websocket");- // 獲取 STOMP 子協議的客戶端對象
- stompClient = Stomp.over(socket);
- // 向伺服器發起websocket連接並發送CONNECT幀
- stompClient.connect({},
function
(frame) { - // 連接成功時(伺服器響應 CONNECTED 幀)的回調方法
- // setConnected(true);
- console.log("Connected: " + frame);
- stompClient.subscribe("/topic/greetings",
function
(greeting) { - showGreeting(JSON.parse(greeting.body).content);
- });
- },
function
errorCallBack(error) { - // 連接失敗時(伺服器響應 ERROR 幀)的回調方法
- });
- }
function
showGreeting(content) {- $("#daiban_count").text(content);
- }
- $(
function
() { - // 監聽信息
- connect();
- });
7.需要源碼,去git下載,下載地址是:spring-websocket
TAG:程序員小新人學習 |