| src/main/java/com/nq/ws/WebSocketClientBeanConfig.java | ●●●●● patch | view | raw | blame | history | |
| src/main/java/com/nq/ws/WebsocketRunClient.java | ●●●●● patch | view | raw | blame | history | |
| src/main/java/com/nq/ws/WsClientConfig.java | ●●●●● patch | view | raw | blame | history |
src/main/java/com/nq/ws/WebSocketClientBeanConfig.java
@@ -1,46 +1,48 @@ //package com.nq.ws; // // //import com.nq.enums.EStockType; //import com.nq.utils.PropertiesUtil; //import lombok.extern.slf4j.Slf4j; //import org.java_websocket.client.WebSocketClient; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; // //import java.net.URI; //import java.util.HashMap; //import java.util.Map; // //@Slf4j //@Configuration //public class WebSocketClientBeanConfig { // // // @Bean // public Map<String, WebSocketClient> websocketRunClientMap() { // // Map<String, WebSocketClient> retMap = new HashMap<>(2); // try { // WebsocketRunClient websocketRunClient = new WebsocketRunClient(new URI("wss://ws.durocaspitall.com/websocket-server"),EStockType.IN); // websocketRunClient.connect(); // websocketRunClient.setConnectionLostTimeout(0); // new Thread(() -> { // while (true) { // try { // Thread.sleep(8000); // websocketRunClient.send("heartbeat".getBytes()); // } catch (Exception e) { // websocketRunClient.reconnect(); // websocketRunClient.setConnectionLostTimeout(0); // } // } // }).start(); // } catch (Exception e) { // } // // return retMap; // } // // //} package com.nq.ws; import com.nq.enums.EStockType; import com.nq.utils.PropertiesUtil; import lombok.extern.slf4j.Slf4j; import org.java_websocket.client.WebSocketClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.net.URI; import java.util.HashMap; import java.util.Map; @Slf4j @Configuration public class WebSocketClientBeanConfig { @Bean public Map<String, WebSocketClient> websocketRunClientMap() { Map<String, WebSocketClient> retMap = new HashMap<>(2); try { WebsocketRunClient websocketRunClient = new WebsocketRunClient(new URI(PropertiesUtil.getProperty("JS_IN_WS_URL")),EStockType.IN); websocketRunClient.connect(); websocketRunClient.setConnectionLostTimeout(0); new Thread(() -> { while (true) { try { Thread.sleep(8000); websocketRunClient.send("heartbeat".getBytes()); } catch (Exception e) { websocketRunClient.reconnect(); websocketRunClient.setConnectionLostTimeout(0); } } }).start(); } catch (Exception e) { } return retMap; } } src/main/java/com/nq/ws/WebsocketRunClient.java
@@ -1,120 +1,129 @@ //package com.nq.ws; // //import com.fasterxml.jackson.core.JsonProcessingException; //import com.fasterxml.jackson.databind.ObjectMapper; //import com.google.gson.Gson; //import com.google.gson.reflect.TypeToken; //import com.nq.enums.EStockType; //import com.nq.pojo.StockRealTimeBean; //import com.nq.service.IMandatoryLiquidationService; //import com.nq.service.impl.MandatoryLiquidationService; //import com.nq.utils.ApplicationContextRegisterUtil; //import com.nq.utils.redis.RedisKeyUtil; //import lombok.extern.slf4j.Slf4j; //import org.apache.http.HttpResponse; //import org.apache.http.client.HttpClient; //import org.apache.http.client.entity.UrlEncodedFormEntity; //import org.apache.http.client.methods.HttpPost; //import org.apache.http.impl.client.HttpClients; //import org.apache.http.message.BasicNameValuePair; //import org.java_websocket.client.WebSocketClient; //import org.java_websocket.handshake.ServerHandshake; //import org.springframework.context.ApplicationContext; // //import java.io.IOException; //import java.lang.reflect.Type; //import java.net.URI; //import java.nio.charset.StandardCharsets; //import java.util.*; // //@Slf4j //public class WebsocketRunClient extends WebSocketClient { // // private EStockType eStockType; // public WebsocketRunClient(URI serverUri, // EStockType eStockType // ) { // super(serverUri); // this.eStockType = eStockType; // } // // private static HttpClient httpClient = HttpClients.createDefault(); // 单例化 HttpClient // // // private static HttpPost httpPost; // static { // httpPost = new HttpPost("http://127.0.0.1:8001/api/sendNotification"); // 初始化 HttpPost // } // // @Override // public void onOpen(ServerHandshake serverHandshake) { // send(("key:"+ eStockType.getStockKey()+":"+eStockType.getContryId()).getBytes()); // } // // @Override // public void onMessage(String s) { // if(!s.equals("pong") && !s.equals("身份验证成功")){ // Map<String, String> stringObjectMap = jsonToMap(s); // StockRealTimeBean stockRealTimeBean = new StockRealTimeBean(); // stockRealTimeBean.setPid(stringObjectMap.get("Id").toString()); // stockRealTimeBean.setLast(stringObjectMap.get("Last").toString()); // stockRealTimeBean.setBid(stringObjectMap.get("Bid").toString()); // stockRealTimeBean.setAsk(stringObjectMap.get("Ask").toString()); // stockRealTimeBean.setHigh(stringObjectMap.get("High").toString()); // stockRealTimeBean.setLow(stringObjectMap.get("Low").toString()); // stockRealTimeBean.setPc(stringObjectMap.get("Chg").toString()); // stockRealTimeBean.setPcp(stringObjectMap.get("ChgPct").toString()+"%"); // stockRealTimeBean.setTime(stringObjectMap.get("Time").toString()); // RedisKeyUtil.setCacheRealTimeStock(EStockType.IN,stockRealTimeBean); // ObjectMapper objectMapper = new ObjectMapper(); // try { // if(!stockRealTimeBean.getPcp().contains("-")){ // stockRealTimeBean.setPcp("+"+stringObjectMap.get("ChgPct").toString()+"%"); // } // String json = objectMapper.writeValueAsString(stockRealTimeBean); // sendLoca(json); // StockRealTimeBean stockDetailBean = new Gson().fromJson(s, StockRealTimeBean.class); // RedisKeyUtil.setCacheRealTimeStock(EStockType.IN,stockDetailBean); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // // } // } // // public static Map<String, String> jsonToMap(String json) { // Gson gson = new Gson(); // Type type = new TypeToken<Map<String, String>>(){}.getType(); // return gson.fromJson(json, type); // } // // @Override // public void onClose(int i, String s, boolean b) { // log.info("websocket 印度股票 关闭"+1); // } // // @Override // public void onError(Exception e) { // log.info("websocket 错误"); // } // // public void sendLoca(String message) { // try { // // 准备 form-data 参数 // List<BasicNameValuePair> params = new ArrayList<>(); // params.add(new BasicNameValuePair("message", message)); // // // 设置编码格式为 UTF-8 // UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8); // httpPost.setEntity(entity); // 设置 HttpPost 对象的参数 // // // 发送请求 // HttpResponse response = httpClient.execute(httpPost); // // // 处理响应 // int statusCode = response.getStatusLine().getStatusCode(); // } catch (IOException e) { // log.error("Http 请求错误", e); // } // } //} package com.nq.ws; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.nq.enums.EStockType; import com.nq.pojo.StockRealTimeBean; import com.nq.service.IMandatoryLiquidationService; import com.nq.service.impl.MandatoryLiquidationService; import com.nq.utils.ApplicationContextRegisterUtil; import com.nq.utils.redis.RedisKeyUtil; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.lang.reflect.Type; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.*; @Slf4j public class WebsocketRunClient extends WebSocketClient { private EStockType eStockType; public WebsocketRunClient(URI serverUri, EStockType eStockType ) { super(serverUri); this.eStockType = eStockType; } private static HttpClient httpClient = HttpClients.createDefault(); // 单例化 HttpClient private static HttpPost httpPost; static { httpPost = new HttpPost("http://127.0.0.1:8001/api/sendNotification"); // 初始化 HttpPost } @Override public void onOpen(ServerHandshake serverHandshake) { send(("key:"+ eStockType.getStockKey()+":"+eStockType.getContryId()).getBytes()); Timer heartbeatTimer; // 启动心跳定时器 heartbeatTimer = new Timer(); heartbeatTimer.schedule(new TimerTask() { @Override public void run() { send(("key:"+ eStockType.getStockKey()+":"+eStockType.getContryId()).getBytes()); } }, 0, 3000); // 每3秒发送一次心跳消息 } @Override public void onMessage(String s) { if(!s.equals("pong") && !s.equals("身份验证成功")){ Map<String, String> stringObjectMap = jsonToMap(s); StockRealTimeBean stockRealTimeBean = new StockRealTimeBean(); stockRealTimeBean.setPid(stringObjectMap.get("Id").toString()); stockRealTimeBean.setLast(stringObjectMap.get("Last").toString()); stockRealTimeBean.setBid(stringObjectMap.get("Bid").toString()); stockRealTimeBean.setAsk(stringObjectMap.get("Ask").toString()); stockRealTimeBean.setHigh(stringObjectMap.get("High").toString()); stockRealTimeBean.setLow(stringObjectMap.get("Low").toString()); stockRealTimeBean.setPc(stringObjectMap.get("Chg").toString()); stockRealTimeBean.setPcp(stringObjectMap.get("ChgPct").toString()+"%"); stockRealTimeBean.setTime(stringObjectMap.get("Time").toString()); RedisKeyUtil.setCacheRealTimeStock(EStockType.IN,stockRealTimeBean); ObjectMapper objectMapper = new ObjectMapper(); try { if(!stockRealTimeBean.getPcp().contains("-")){ stockRealTimeBean.setPcp("+"+stringObjectMap.get("ChgPct").toString()+"%"); } String json = objectMapper.writeValueAsString(stockRealTimeBean); sendLoca(json); StockRealTimeBean stockDetailBean = new Gson().fromJson(s, StockRealTimeBean.class); RedisKeyUtil.setCacheRealTimeStock(EStockType.IN,stockDetailBean); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } public static Map<String, String> jsonToMap(String json) { Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>(){}.getType(); return gson.fromJson(json, type); } @Override public void onClose(int i, String s, boolean b) { log.info("websocket 印度股票 关闭"+1); } @Override public void onError(Exception e) { log.info("websocket 错误"); } public void sendLoca(String message) { try { // 准备 form-data 参数 List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("message", message)); // 设置编码格式为 UTF-8 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8); httpPost.setEntity(entity); // 设置 HttpPost 对象的参数 // 发送请求 HttpResponse response = httpClient.execute(httpPost); // 处理响应 int statusCode = response.getStatusLine().getStatusCode(); } catch (IOException e) { log.error("Http 请求错误", e); } } } src/main/java/com/nq/ws/WsClientConfig.java
@@ -1,169 +1,169 @@ package com.nq.ws; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.nq.enums.EStockType; import com.nq.pojo.StockRealTimeBean; import com.nq.service.IMandatoryLiquidationService; import com.nq.service.impl.MandatoryLiquidationService; import com.nq.utils.ApplicationContextRegisterUtil; import com.nq.utils.PropertiesUtil; import com.nq.utils.redis.RedisKeyUtil; import com.nq.ws.client.IO; import com.nq.ws.client.Socket; import io.socket.emitter.Emitter; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * soket-io */ @Slf4j @Configuration public class WsClientConfig { private static final String SERVER_URL = PropertiesUtil.getProperty("JS_IN_HTTP_API"); private static final String AUTH_KEY = PropertiesUtil.getProperty("JS_IN_KEY"); private static final String ROOM_ID = "14"; private static Socket socket; private static HttpClient httpClient = HttpClients.createDefault(); // 单例化 HttpClient private static HttpPost httpPost; static { httpPost = new HttpPost("http://127.0.0.1:8001/api/sendNotification"); // 初始化 HttpPost } @Bean public void websocketRunClientMap() { connectToServer(); } private static void connectToServer() { IO.Options options = new IO.Options(); options.reconnection = true; options.reconnectionDelay = 1000; try { socket = IO.socket(new URI(SERVER_URL), options); } catch (URISyntaxException e) { log.error("Invalid URI", e); return; } socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() { @Override public void call(Object... args) { authenticate(); } }); socket.on("marketData", new Emitter.Listener() { @Override public void call(Object... args) { send(args[0].toString()); StockRealTimeBean stockDetailBean = new Gson().fromJson(args[0].toString(), StockRealTimeBean.class); RedisKeyUtil.setCacheRealTimeStock(EStockType.IN,stockDetailBean); } }); socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() { @Override public void call(Object... args) { log.error("socketIo连接错误: " + args[0]); } }); socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() { @Override public void call(Object... args) { log.error("socketIo 断开连接: " + args[0]); if (!socket.connected()) { log.error("socketIo 开始重连: " + args[0]); reconnect(); } } }); socket.connect(); } public static Map<String, Object> jsonToMap(String json) { Gson gson = new Gson(); Type type = new TypeToken<Map<String, Object>>(){}.getType(); return gson.fromJson(json, type); } private static void reconnect() { new Thread(new Runnable() { @Override public void run() { while (!socket.connected()) { try { log.error("socketIo 开始重连"); socket.connect(); Thread.sleep(5000); // 重连间隔,单位毫秒 } catch (InterruptedException e) { log.error("重连被中断", e); } } } }).start(); } private static void authenticate() { log.info("socketIo---->开始连接"); if (socket != null && socket.connected()) { JSONObject authData = new JSONObject(); try { authData.put("key", AUTH_KEY); authData.put("roomId", ROOM_ID); socket.emit("authenticate", authData); log.info("socketIo---->连接成功"); } catch (JSONException e) { log.error("socketIo认证错误:"+e.getMessage(), e); } } } private static void send(String message) { try { // 准备 form-data 参数 List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("message", message)); // 设置编码格式为 UTF-8 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8); httpPost.setEntity(entity); // 设置 HttpPost 对象的参数 // 发送请求 HttpResponse response = httpClient.execute(httpPost); // 处理响应 int statusCode = response.getStatusLine().getStatusCode(); } catch (IOException e) { log.error("Http 请求错误", e); } } } //package com.nq.ws; // //import com.google.gson.Gson; //import com.google.gson.reflect.TypeToken; //import com.nq.enums.EStockType; //import com.nq.pojo.StockRealTimeBean; //import com.nq.service.IMandatoryLiquidationService; //import com.nq.service.impl.MandatoryLiquidationService; //import com.nq.utils.ApplicationContextRegisterUtil; //import com.nq.utils.PropertiesUtil; //import com.nq.utils.redis.RedisKeyUtil; //import com.nq.ws.client.IO; //import com.nq.ws.client.Socket; //import io.socket.emitter.Emitter; //import lombok.extern.slf4j.Slf4j; //import org.apache.http.HttpResponse; //import org.apache.http.client.HttpClient; //import org.apache.http.client.entity.UrlEncodedFormEntity; //import org.apache.http.client.methods.HttpPost; //import org.apache.http.impl.client.HttpClients; //import org.apache.http.message.BasicNameValuePair; //import org.json.JSONException; //import org.json.JSONObject; //import org.springframework.context.ApplicationContext; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; // //import java.io.IOException; //import java.lang.reflect.Type; //import java.net.URI; //import java.net.URISyntaxException; //import java.nio.charset.StandardCharsets; //import java.text.SimpleDateFormat; //import java.util.ArrayList; //import java.util.Date; //import java.util.List; //import java.util.Map; // ///** // * soket-io // */ //@Slf4j //@Configuration //public class WsClientConfig { // // private static final String SERVER_URL = PropertiesUtil.getProperty("JS_IN_HTTP_API"); // private static final String AUTH_KEY = PropertiesUtil.getProperty("JS_IN_KEY"); // private static final String ROOM_ID = "14"; // private static Socket socket; // // private static HttpClient httpClient = HttpClients.createDefault(); // 单例化 HttpClient // // // private static HttpPost httpPost; // static { // httpPost = new HttpPost("http://127.0.0.1:8001/api/sendNotification"); // 初始化 HttpPost // } // @Bean // public void websocketRunClientMap() { // connectToServer(); // } // // private static void connectToServer() { // IO.Options options = new IO.Options(); // options.reconnection = true; // options.reconnectionDelay = 1000; // // try { // socket = IO.socket(new URI(SERVER_URL), options); // } catch (URISyntaxException e) { // log.error("Invalid URI", e); // return; // } // // socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() { // @Override // public void call(Object... args) { // authenticate(); // } // }); // // socket.on("marketData", new Emitter.Listener() { // @Override // public void call(Object... args) { // send(args[0].toString()); // StockRealTimeBean stockDetailBean = new Gson().fromJson(args[0].toString(), StockRealTimeBean.class); // RedisKeyUtil.setCacheRealTimeStock(EStockType.IN,stockDetailBean); // } // }); // // socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() { // @Override // public void call(Object... args) { // log.error("socketIo连接错误: " + args[0]); // } // }); // // socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() { // @Override // public void call(Object... args) { // log.error("socketIo 断开连接: " + args[0]); // if (!socket.connected()) { // log.error("socketIo 开始重连: " + args[0]); // reconnect(); // } // } // }); // // socket.connect(); // } // // public static Map<String, Object> jsonToMap(String json) { // Gson gson = new Gson(); // Type type = new TypeToken<Map<String, Object>>(){}.getType(); // return gson.fromJson(json, type); // } // // private static void reconnect() { // new Thread(new Runnable() { // @Override // public void run() { // while (!socket.connected()) { // try { // log.error("socketIo 开始重连"); // socket.connect(); // Thread.sleep(5000); // 重连间隔,单位毫秒 // } catch (InterruptedException e) { // log.error("重连被中断", e); // } // } // } // }).start(); // } // // private static void authenticate() { // log.info("socketIo---->开始连接"); // if (socket != null && socket.connected()) { // JSONObject authData = new JSONObject(); // try { // authData.put("key", AUTH_KEY); // authData.put("roomId", ROOM_ID); // socket.emit("authenticate", authData); // log.info("socketIo---->连接成功"); // } catch (JSONException e) { // log.error("socketIo认证错误:"+e.getMessage(), e); // } // } // } // // private static void send(String message) { // try { // // 准备 form-data 参数 // List<BasicNameValuePair> params = new ArrayList<>(); // params.add(new BasicNameValuePair("message", message)); // // // 设置编码格式为 UTF-8 // UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8); // httpPost.setEntity(entity); // 设置 HttpPost 对象的参数 // // // 发送请求 // HttpResponse response = httpClient.execute(httpPost); // // // 处理响应 // int statusCode = response.getStatusLine().getStatusCode(); // } catch (IOException e) { // log.error("Http 请求错误", e); // } // } //}