Spring Boot 2.x整合Websocket(基于Spring Boot 2.x 前后端分離 iview admin vue 集成activiti工作流 模型設計器 動態數據權限 )


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", "您收到了新的消息");
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容