已有Kafka服務,經過kafka服務數據(GPS)落地到本地磁盤(以文本文件存儲)。現要根據echarts實現一個實時車輛的地圖。javascript
websocket是HTML5開始提供的一種在單位TCP鏈接上進行全雙工通信的協議。在websocket api中,瀏覽器和服務器只須要作一次握手的動做,而後瀏覽器和服務器之間就造成了一條快速通道。二者之間就能夠數據互相傳送。html
package com.ykkj.weiyi.socket; import org.springframework.stereotype.Component; import org.springframework.web.socket.server.standard.SpringConfigurator; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; /** * @ServerEndpoint 註解是一個類層次的註解,它的功能主要是將目前的類定義成一個websocket服務器端, * 註解的值將被用於監聽用戶鏈接的終端訪問URL地址,客戶端能夠經過這個URL來鏈接到WebSocket服務器端 */ @ServerEndpoint(value = "/websocket") public class CommodityServer { //靜態變量,用來記錄當前在線鏈接數。應該把它設計成線程安全的。 private static int onlineCount = 0; //concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通訊的話,可使用Map來存放,其中Key能夠爲用戶標識 public static CopyOnWriteArraySet<CommodityServer> webSocketSet = new CopyOnWriteArraySet<CommodityServer>(); //與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據 private Session session; /** * 鏈接創建成功調用的方法 * * @param session 可選的參數。session爲與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據 */ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在線數加1 System.out.println("有新鏈接加入!當前在線人數爲" + getOnlineCount()); } /** * 鏈接關閉調用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //從set中刪除 subOnlineCount(); //在線數減1 System.out.println("有一鏈接關閉!當前在線人數爲" + getOnlineCount()); } /** * 收到客戶端消息後調用的方法 * * @param message 客戶端發送過來的消息 * @param session 可選的參數 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("來自客戶端的消息:" + message); //羣發消息 for (CommodityServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } } } /** * 發生錯誤時調用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println("發生錯誤"); error.printStackTrace(); } /** * 這個方法與上面幾個方法不同。沒有用註解,是根據本身須要添加的方法。 * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); //this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { CommodityServer.onlineCount++; } public static synchronized void subOnlineCount() { CommodityServer.onlineCount--; } }
前端前端
<!DOCTYPE html> <html> <head> <title>Java後端WebSocket的Tomcat實現</title> </head> <body> Welcome<br/><input id="text" type="text"/> <button onclick="send()">發送消息</button> <hr/> <button onclick="closeWebSocket()">關閉WebSocket鏈接</button> <hr/> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; //判斷當前瀏覽器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8081/onepic/websocket"); } else { alert('當前瀏覽器 Not support websocket') } //鏈接發生錯誤的回調方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket鏈接發生錯誤"); }; //鏈接成功創建的回調方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket鏈接成功"); } //接收到消息的回調方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //鏈接關閉的回調方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket鏈接關閉"); } //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket鏈接,防止鏈接還沒斷開就關閉窗口,server端會拋異常。 window.onbeforeunload = function () { closeWebSocket(); } //將消息顯示在網頁上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //關閉WebSocket鏈接 function closeWebSocket() { websocket.close(); } //發送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script> </html>
webSocketSet
設置爲全局靜態變量,爲其餘類提供調用java
public static CopyOnWriteArraySet<CommodityServer> webSocketSet = new CopyOnWriteArraySet<CommodityServer>(); 複製代碼
服務端都是用註解實現的 @ServerEndpoint @OnOpen @OnClose @OnMessage @OnErrorgit
Tomcat7.0.47以上版本支持websocket1.0github
pom中添加jar支持web
<dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency>
Kafka是一個分佈式的、可分區的、可複製的消息系統。spring
window系統搭建kafka環境,請參照個人《 kafka環境搭建(windows) 》筆記apache
package com.ykkj.weiyi.socket; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import static com.ykkj.weiyi.socket.CommodityServer.webSocketSet; public class ConsumerKafka extends Thread { private KafkaConsumer<String, String> consumer; private String topic = "test.topic"; public ConsumerKafka() { } @Override public void run() { //加載kafka消費者參數 Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "ytna"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("session.timeout.ms", "15000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); //建立消費者對象 consumer = new KafkaConsumer<String, String>(props); consumer.subscribe(Arrays.asList(this.topic)); //死循環,持續消費kafka while (true) { try { //消費數據,並設置超時時間 ConsumerRecords<String, String> records = consumer.poll(100); //Consumer message for (ConsumerRecord<String, String> record : records) { //Send message to every client for (CommodityServer webSocket : webSocketSet) { webSocket.sendMessage(record.value()); } } } catch (IOException e) { System.out.println(e.getMessage()); continue; } } } public void close() { try { consumer.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } //供測試用,若經過tomcat啓動需經過其餘方法啓動線程 public static void main(String[] args) { ConsumerKafka consumerKafka = new ConsumerKafka(); consumerKafka.start(); } }
注意topic 和 bootstrap.servers配置bootstrap
package com.ykkj.weiyi.socket; public class RunThread { public RunThread() { ConsumerKafka kafka = new ConsumerKafka(); kafka.start(); } }
<listener> <listener-class>com.ykkj.weiyi.socket.RunThread</listener-class> </listener>
import static com.ykkj.weiyi.socket.CommodityServer.webSocketSet;
這裏只是作了技術驗證,尚未真正實現。真實場景下,kafka獲取到的數據須要進行數據清洗,把不符合當前規範的數據清洗掉,而且按照前端展現須要的格式組裝數據。
https://blog.csdn.net/lw_ghy/article/details/73252904
https://blog.csdn.net/liu857279611/article/details/70157012
做者:jinshw連接:https://juejin.im/post/5b20e2e16fb9a01e2c698c51來源:掘金著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。