天天看點

SpringBoot整合Websocket,實作廣播式和給特定使用者發送消息總結:這裡我采用程式設計式使用。參考資料上面可能出現前端總404問題,轉用原生的websocket。

文章目錄

  • 總結:
  • 這裡我采用程式設計式使用。
  • 參考資料
  • 上面可能出現前端總404問題,轉用原生的websocket。
    • 注意點

總結:

  • 廣播式:通知所有人,簡單。隻需要訂閱一個位址就行。
  • 特定使用者: 2種做法。
    • 每個人訂閱的位址不一樣。
    • 程式設計式獲得websocket,然後操作它就行了。

這裡我采用程式設計式使用。

  • 配置bean:
import org.springframework.context.annotation.Bean;
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;

/**
 * 服務推送: wss://www.example.com/websocket/SendTo/topic/greetings
 * 前端請求: wss://www.example.com/websocket/MessageMapping/topic/MessageMapping
 * socket核心配置容器
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //
        config.enableSimpleBroker("/MessageMapping");// /users 預設通知
        config.setApplicationDestinationPrefixes("/SendTo");
        //設定字首  預設是user 可以修改  點對點時使用 , 不使用
        config.setUserDestinationPrefix("/user-wlh/");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //
        registry.addEndpoint("/websocket").withSockJS();
    }

}
           
  • 具體代碼:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/checkcenter")
public class CheckCenterController {
	/**
	 * session操作類

	@Autowired
	SocketSessionRegistry webAgentSessionRegistry;	 */
	/**
	 * 消息發送工具
	 */
	@Autowired
	private SimpMessagingTemplate template;

	@RequestMapping(value = "/index")
	public String index() {
		template.convertAndSendToUser("userId", "/topic/greetings", "我的消息");
		return "/index";
	}

	/**
	 * 使用者廣播
	 * 發送消息廣播  用于内部發送使用
	 *
	 * @param request
	 * @return
	 */
	@MessageMapping("/change-notice1")
	public void greeting1(String value) {
		this.template.convertAndSend("/topic/notice", value);
	}
	@MessageMapping("/change-notice")
	@SendTo("/topic/notice")
	public String greeting(String value) {
		return value;
	}


	/**
	 * 同樣的發送消息   隻不過是ws版本  http請求不能通路
	 *
	 * @param message
	 * @return
	 * @throws Exception
	 */
	@MessageMapping("/msg/hellosingle")
	public void greeting2(String userId) throws Exception {
		//這裡沒做校驗
		template.convertAndSendToUser(userId, "/topic/greetings", "我的消息");
	}

} 
           

參考資料

  • SpringBoot2.0內建WebSocket,實作背景向前端推送資訊
看他的原理,demo不通
  • 基于spring boot 2.x的websocket示例
基本demo,隻有全局推送,全局推送的簡易寫法。
  • Spring WebSocket初探1 (Spring WebSocket入門教程)
這個是java後端。
  • Spring WebSocket初探2 (Spring WebSocket入門教程)
這個是js前端。
  • SpringBoot整合Websocket,實作廣播式和給特定使用者發送消息,不需要登入即可發送消息。
有demo和
  • SpringBoot WebSocket 發送消息給指定的使用者–注解版
通過@SendToUser發送到特定的使用者
  • Spring websocket+Stomp+SockJS 實時通信詳解
boot全家桶使用方案。

上面可能出現前端總404問題,轉用原生的websocket。

見下

  • SpringBoot2內建WebSocket
實作廣播式
  • websocket @ServerEndpoint(value = “/websocket/{ip}”)詳解
給特定使用者發送消息
  • WebSocket使用javax.websocket.RemoteEndpoint.Basic.sendObject(Object arg0)向頁面方法發送對象
放棄使用,這個更加麻煩。

注意點

  • spring-boot-junit需要添加

    @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

  • app類不能加注解websocket注解啟動,否則報錯。

繼續閱讀