spring boot websocket 實時消息推送和數據展現

1、實現目標

  • 一、在線聊天,客服聊天,聊天室
  • 二、業務數據實時展現,自動更新

2、實踐步驟

如下是爲了實現:業務數據實時展現,自動更新前端

1. Maven引入

<dependency>  
   <groupId>org.springframework.boot</groupId>  
   <artifactId>spring-boot-starter-websocket</artifactId>  
</dependency> 
複製代碼

2. 建立配置文件

WebSocketConfigjava

/** * 開啓WebSocket支持 * @author zhengkai */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

複製代碼

3. 建立服務端

@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    //concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據
    private Session session;

    /** * 鏈接創建成功調用的方法 */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        sendMessage("鏈接成功");
    }

    /** * 鏈接關閉調用的方法 */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("有一鏈接關閉!");
    }

    /** * 收到客戶端消息後調用的方法 * * @param queryType 客戶端發送過來的消息 */
    @OnMessage
    public void onMessage(String queryType) {
        log.info("收到信息:" + queryType);

        //羣發消息
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage("hello");
        }
    }

    /** * @param session * @param error */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("發生錯誤");
        error.printStackTrace();
    }

    /** * 實現服務器主動推送 */
    public void sendMessage(Object message) {
        try {
            this.session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** * 實現服務器主動羣發消息 */
    public static void sendInfo(Object message) {
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage(message);
        }
    }
}

複製代碼

4. 前端發起websocket請求

<script> 
    var socket;  
    if(typeof(WebSocket) == "undefined") {  
        console.log("您的瀏覽器不支持WebSocket");  
    }else{  
        console.log("您的瀏覽器支持WebSocket");  
        	//實現化WebSocket對象,指定要鏈接的服務器地址與端口  創建鏈接  
            socket = new WebSocket("ws://localhost:8080/webscoket");
            //打開事件  
            socket.onopen = function() {  
                console.log("Socket 已打開");  
                //socket.send("這是來自客戶端的消息" + location.href + new Date());  
            };  
            //得到消息事件  
            socket.onmessage = function(msg) {  
                console.log(msg.data);  
                //發現消息進入    開始處理前端觸發邏輯
            };  
            //關閉事件  
            socket.onclose = function() {  
                console.log("Socket已關閉");  
            };  
            //發生了錯誤事件  
            socket.onerror = function() {  
                alert("Socket發生了錯誤");  
                //此時能夠嘗試刷新頁面
            } 
    }
    </script> 
複製代碼

3、實踐中會遇到的問題

1. 前端發起websocket請求, 卻沒法鏈接websocket

  • 錯誤一:被權限攔截,例如spring security 解決方式:放開權限或容許訪問
// spring security
.antMatchers(
    "/websocket"
    )
.permitAll()

複製代碼
  • 錯誤二:請求的websocket地址錯誤
@ServerEndpoint(value = "/websocket")

對應的地址是:ws://localhost:8080/webscoket
複製代碼
  • 錯誤三:被AOP攔截
@Pointcut("execution(public * com.xxx.xxx.controller..*(..))")
public void webLog() {
}
複製代碼

解決辦法web

// 排除攔截
@Pointcut("execution(public * com.xxx.xxx.controller..*(..)) && !execution(public * com.xxx.xxx.controller.xxx*(..))")
public void webLog() {
}
複製代碼

2. 在WebSocketServer中,沒法注入Bean,沒法使用@Autowired

即你按以下方式直接使用@Autowired,會報錯spring

@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
    @Autowired
    ChartDataService chartDataService;
}
複製代碼

在WebSocket中, 因 SpringBoot+WebSocket 對每一個客戶端鏈接都會建立一個 WebSocketServer(@ServerEndpoint 註解對應的) 對象,Bean 注入操做會被直接略過,於是手動注入一個全局變量(即你須要注入的bean)瀏覽器

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    // 在這裏注入你須要的bean
    @Autowired
    public void setMessageService(ChartDataService chartDataService) {
        WebSocketServer.chartDataService = chartDataService;
        // ...
    }
}

複製代碼

使用你注入的bean安全

@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {

    public static ChartDataService chartDataService;

複製代碼

此方式經實踐,有效bash

其餘解決方式: stackoverflow.com/questions/2…服務器

  • 1.使用@Inject
@ServerEndpoint("/ws")
public class MyWebSocket {   
    @Inject
    private ObjectMapper objectMapper;
}
複製代碼
  • 2.使用SpringConfigurator
@ServerEndpoint(value = "/ws", configurator = SpringConfigurator.class)
複製代碼
  • 3.使用@PostConstruct
@PostConstruct
public void init(){
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
複製代碼

通過實踐,上述三種方式,對於我而言,均無效websocket

參考連接:blog.csdn.net/moshowgame/…session

相關文章
相關標籤/搜索