第一步,maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
第二步,Configuration
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
//简单来说就是设置一个节点,路径名字
//前端js初始化 new SockJS('/项目名称/xunWS');
stompEndpointRegistry.addEndpoint("/xunWS").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//可以理解为前缀,参数可以填多个
//@SendTo("/topic/orderN")
registry.enableSimpleBroker("/topic","/queue");
}
}
第三步,Controller
"/topic/orderN"其实就是一个标识,发送和接收时用到。"/topic"是Configuration中设置的registry.enableSimpleBroker("/topic");
@Controller
public class WSOrderController extends BaseController {
@Autowired
private SimpMessagingTemplate template;
@MessageMapping("/orderN")
@SendTo("/topic/orderN")
public ConfigModel orderNotify(ConfigModel msg){
if (msg instanceof ConfigModel) {
return msg;
}else {
ConfigModel m = new ConfigModel();
m.setConf_value(msg.toString());
m.setConf_key("c_msg");
m.setConf_id(123456);
return m;
}
}
@Scheduled(cron = "0 0/1 * * * ?")//每分钟执行一次
public void demo() {
//后台发送,第一参数是标识,第二参数是Object。和ios的通知中心类似
//前端js接收设置该标识就可以接收该消息,其中不会跑orderNotify方法
//后台直接调用orderNotify方法,前端是不会触发接收器的
//即使orderNotify方法去掉,也能行得通
template.convertAndSend("/topic/orderN", new Date().toString());
}
}////
第四步,js页面。jquery.min.js sockjs.min.js stomp.min.js
<script th:inline="javascript">
/*<![CDATA[*/
$(function(){
connect();
setInterval("send()",9000);
});
var stompClient;
function connect() {
var sockjs = new SockJS('/项目名称/xunWS');
stompClient = Stomp.over(sockjs);
stompClient.connect({},function (frame) {
console.log('===========Connected:'+frame);
//设置接收标识[路径]
stompClient.subscribe('/topic/orderN',function (response) {
//返回来的是json数据
console.log("=========="+response.body);
});
});
}
function send() {
//js端发送信息,这个会跑后台orderNotify方法,"/orderN"和 @MessageMapping("/orderN")对应
//orderNotify方法设置了@SendTo("/topic/orderN") ,执行完orderNotify方法后会触发上面的subscribe。
stompClient.send("/orderN", {}, JSON.stringify({'conf_id':'1000','conf_key':'c_duo','conf_value':'我爱duoduo'}));
}
/*]]>*/
</script>