- 宣傳官網 http://xb.exrick.cn
- 在線Demo http://xboot.exrick.cn
- 開源版Github地址 https://github.com/Exrick/x-boot
- 開發文檔 https://www.kancloud.cn/exrick/xboot/1009234
- 獲取完整版 http://xpay.exrick.cn/pay?xboot
在這里插入圖片描述
Stomp是一種簡單(流)文本定向消息協議,提供了一個可互操作的鏈接格式。允許stomp客戶端與任意stomp消息代理(Broker)進行交互。STOMP協議由于設計簡單,易于開發客戶端,因此在多種語言和多種平臺上得到廣泛地應用。
- 添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 配置類
/**
* @author Exrickx
*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {
/**
* 注冊stomp端點
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// 允許使用socketJs方式訪問 即可通過http://IP:PORT/ws來和服務端websocket連接
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
/**
* 配置信息代理
* @param registry
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// 訂閱Broker名稱 user點對點 topic廣播即群發
registry.enableSimpleBroker("/user","/topic");
// 全局(客戶端)使用的消息前綴
registry.setApplicationDestinationPrefixes("/app");
// 點對點使用的前綴 無需配置 默認/user
registry.setUserDestinationPrefix("/user");
}
}
- 由于只做廣播和點對點的消息推送,這里只用到訂閱發布
@Autowired
private SimpMessagingTemplate messagingTemplate;
// 廣播
messagingTemplate.convertAndSend("/topic/subscribe", "您收到了新的系統消息");
// 通過用戶ID實現點對點
messagingTemplate.convertAndSendToUser(id,"/queue/subscribe", "您收到了新的消息");