springboot,websocket,后台主动推送消息
1.pom
4.0.0
com.liuxl.cartmall
spring-websocket
0.0.1-SNAPSHOT
jar
spring-websocket
Demo project for Spring Boot
https://spring.io/guides/gs/messaging-stomp-websocket/
org.springframework.boot
spring-boot-starter-parent
2.0.2.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-websocket
org.webjars
webjars-locator-core
org.webjars
sockjs-client
1.0.2
org.webjars
stomp-websocket
2.3.3
org.webjars
bootstrap
3.3.7
org.webjars
jquery
3.1.0
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
2.SpringWebsocketApplication springboot 启动类
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
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 WebSocketConfig implements 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
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;
}
}
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
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
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
https://github.com/lxldemon/spring-websocket.git
https://github.com/lxldemon/spring-websocket.