引入jar包
<dependency><!-- 5.引入websocket--> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
1 配置config
package com.test.domi.config; 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; @Configuration // @EnableWebSocketMessageBroker注解用於開啟使用STOMP協議來傳輸基於代理(MessageBroker)的消息,這時候控制器(controller) // 開始支持@MessageMapping,就像是使用@requestMapping一樣。 @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
/*將"/hello"路徑注冊為STOMP端點,這個路徑與發送和接收消息的目的路徑有所不同,這是一個端點,客戶端在訂閱或發布消息到目的地址前,要連接該端點,
* 即用戶發送請求url="/applicationName/hello"與STOMP server進行連接。之后再轉發到訂閱url;
* PS:端點的作用——客戶端在訂閱或發布消息到目的地址前,要連接該端點。
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
//注冊一個Stomp的節點(endpoint),並指定使用SockJS協議。記得設置跨域
stompEndpointRegistry.addEndpoint("/endpointAric").setAllowedOrigins("*").withSockJS();
}
/**
* 配置了一個簡單的消息代理,如果不重載,默認情況下回自動配置一個簡單的內存消息代理,用來處理以"/topic"為前綴的消息。這里重載configureMessageBroker()方法,
* 消息代理將會處理前綴為"/topic"和"/queue"的消息。
@Override public void configureMessageBroker(MessageBrokerRegistry registry) { //服務端發送消息給客戶端的域,多個用逗號隔開 registry.enableSimpleBroker("/topic"); //定義一對一推送的時候前綴 //registry.setUserDestinationPrefix("/user"); //定義websoket前綴 //registry.setApplicationDestinationPrefixes("/ws-push"); } }
2 controller
package com.test.domi.controller; import com.google.common.collect.Lists; import com.test.domi.service.impl.WebSocketService; 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 javax.annotation.Resource; import java.util.List; @Controller public class WsController { @Resource private SimpMessagingTemplate template; @MessageMapping("/welcome")//@MessageMapping和@RequestMapping功能類似,用於設置URL映射地址,瀏覽器向服務器發起請求,需要通過該地址。 public void say(String message) throws Exception { template.convertAndSend("/topic/getResponse", message); } }
3 前台頁面