springboot websocket訂單訊息提醒
阿新 • • 發佈:2018-11-26
WebSocketConfig.java
package com.yizhen.config; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * Created by 廖師兄 * 2017-07-30 23:17 */ @Component public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
WebSocket.java
package com.yizhen.service; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import java.util.concurrent.CopyOnWriteArraySet; /** * Created by 廖師兄 * 2017-07-30 23:19 */ @Component @ServerEndpoint("/webSocket") @Slf4j public class WebSocket { private Session session; private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>(); @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); log.info("【websocket訊息】有新的連線, 總數:{}", webSocketSet.size()); } @OnClose public void onClose() { webSocketSet.remove(this); log.info("【websocket訊息】連線斷開, 總數:{}", webSocketSet.size()); } @OnMessage public void onMessage(String message) { log.info("【websocket訊息】收到客戶端發來的訊息:{}", message); } public void sendMessage(String message) { for (WebSocket webSocket: webSocketSet) { log.info("【websocket訊息】廣播訊息, message={}", message); try { webSocket.session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } }
需要訊息提示的介面:
<script type="text/javascript"> var websocket = null; if('WebSocket' in window) { websocket = new WebSocket('ws://bgyzuishuai.s1.natapp.cc/webSocket'); }else { alert('該瀏覽器不支援訂單提醒!'); } websocket.onopen = function (event) { console.log('建立連線'); } websocket.onclose = function (event) { console.log('連線關閉'); } websocket.onmessage = function (event) { console.log('收到訊息:' + event.data) //彈窗提醒, 播放音樂 $('#dingdanxiaoxi').modal('show'); document.getElementById('notice').play(); } websocket.onerror = function () { alert('websocket通訊發生錯誤!'); } window.onbeforeunload = function () { websocket.close(); } </script>
pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
最後@autowired Websocket
使用websocket.sendMessage()傳送訊息