| New file |
| | |
| | | //package com.xcong.excoin.modules.okxKline; |
| | | // |
| | | //import com.alibaba.fastjson.JSON; |
| | | //import com.alibaba.fastjson.JSONArray; |
| | | //import com.alibaba.fastjson.JSONObject; |
| | | //import com.xcong.excoin.utils.RedisUtils; |
| | | //import lombok.extern.slf4j.Slf4j; |
| | | //import org.java_websocket.client.WebSocketClient; |
| | | //import org.java_websocket.handshake.ServerHandshake; |
| | | //import org.springframework.stereotype.Component; |
| | | // |
| | | //import javax.annotation.PostConstruct; |
| | | //import javax.annotation.PreDestroy; |
| | | //import javax.annotation.Resource; |
| | | //import java.net.URI; |
| | | //import java.net.URISyntaxException; |
| | | //import java.nio.channels.ClosedChannelException; |
| | | //import java.util.HashMap; |
| | | //import java.util.Map; |
| | | //import java.util.concurrent.Executors; |
| | | //import java.util.concurrent.ScheduledExecutorService; |
| | | //import java.util.concurrent.ScheduledFuture; |
| | | //import java.util.concurrent.TimeUnit; |
| | | //import java.util.concurrent.atomic.AtomicReference; |
| | | // |
| | | //@Slf4j |
| | | //@Component |
| | | //public class OkxWebSocketClient { |
| | | // |
| | | // private WebSocketClient webSocketClient; |
| | | // private ScheduledExecutorService heartbeatExecutor; |
| | | // private ScheduledFuture<?> pongTimeoutFuture; |
| | | // private final AtomicReference<Long> lastMessageTime = new AtomicReference<>(System.currentTimeMillis()); |
| | | // |
| | | // @Resource |
| | | // private RedisUtils redisUtils; |
| | | // |
| | | // private static final String WS_URL = "wss://ws.okx.com:8443/ws/v5/business"; |
| | | //// private static final String WS_URL = "wss://wspap.okx.com:8443/ws/v5/business"; |
| | | // private static final String[] CHANNELS = { |
| | | // "mark-price-candle1m", "mark-price-candle5m", "mark-price-candle15m", |
| | | // "mark-price-candle30m", "mark-price-candle1H", "mark-price-candle4H", |
| | | // "mark-price-candle1D" |
| | | // }; |
| | | // |
| | | // private static final String[] INST_IDS = { |
| | | // "BTC-USDT", "ETH-USDT", "BNB-USDT", "XRP-USDT", "ADA-USDT", |
| | | // "DOGE-USDT", "DOT-USDT", "UNI-USDT", "LTC-USDT", "LINK-USDT" |
| | | // }; |
| | | // |
| | | // // 心跳超时时间(秒),小于30秒 |
| | | // private static final int HEARTBEAT_INTERVAL = 25; // 增加到25秒 |
| | | // private static final int PONG_TIMEOUT = 15; // 增加到15秒 |
| | | // |
| | | // @PostConstruct |
| | | // public void init() { |
| | | // connect(); |
| | | // startHeartbeat(); |
| | | // } |
| | | // |
| | | // @PreDestroy |
| | | // public void destroy() { |
| | | // if (webSocketClient != null && webSocketClient.isOpen()) { |
| | | // try { |
| | | // webSocketClient.close(); |
| | | // } catch (Exception e) { |
| | | // log.warn("关闭WebSocket连接时发生异常", e); |
| | | // } |
| | | // } |
| | | // if (heartbeatExecutor != null) { |
| | | // heartbeatExecutor.shutdown(); |
| | | // } |
| | | // if (pongTimeoutFuture != null) { |
| | | // pongTimeoutFuture.cancel(true); |
| | | // } |
| | | // } |
| | | // |
| | | // private void connect() { |
| | | // try { |
| | | // URI uri = new URI(WS_URL); |
| | | // webSocketClient = new WebSocketClient(uri) { |
| | | // @Override |
| | | // public void onOpen(ServerHandshake handshake) { |
| | | // log.info("OKX WebSocket连接成功"); |
| | | // lastMessageTime.set(System.currentTimeMillis()); |
| | | // subscribeChannels(); |
| | | // } |
| | | // |
| | | // @Override |
| | | // public void onMessage(String message) { |
| | | // // 更新最后消息时间 |
| | | // lastMessageTime.set(System.currentTimeMillis()); |
| | | // handleWebSocketMessage(message); |
| | | // } |
| | | // |
| | | // @Override |
| | | // public void onClose(int code, String reason, boolean remote) { |
| | | // log.warn("OKX WebSocket连接关闭: code={}, reason={}, remote={}", code, reason, remote); |
| | | // cancelPongTimeout(); |
| | | // // 不能在WebSocket线程内部直接调用reconnect()方法 |
| | | // // 需要在另一个线程中执行重连操作 |
| | | // scheduleReconnect(); |
| | | // } |
| | | // |
| | | // @Override |
| | | // public void onError(Exception ex) { |
| | | // log.error("OKX WebSocket发生错误", ex); |
| | | // // 特别处理连接异常 |
| | | // if (ex instanceof ClosedChannelException) { |
| | | // log.warn("检测到通道关闭,准备重连"); |
| | | // scheduleReconnect(); |
| | | // } |
| | | // } |
| | | // }; |
| | | // |
| | | // webSocketClient.connect(); |
| | | // } catch (URISyntaxException e) { |
| | | // log.error("WebSocket URI格式错误", e); |
| | | // } |
| | | // } |
| | | // |
| | | // private void subscribeChannels() { |
| | | // try { |
| | | // JSONObject subscribeMsg = new JSONObject(); |
| | | // subscribeMsg.put("op", "subscribe"); |
| | | // |
| | | // JSONArray argsArray = new JSONArray(); |
| | | // for (String channel : CHANNELS) { |
| | | // for (String instId : INST_IDS) { |
| | | // JSONObject arg = new JSONObject(); |
| | | // arg.put("channel", channel); |
| | | // arg.put("instId", instId); |
| | | // argsArray.add(arg); |
| | | // } |
| | | // } |
| | | // |
| | | // subscribeMsg.put("args", argsArray); |
| | | // webSocketClient.send(subscribeMsg.toJSONString()); |
| | | // log.info("已发送订阅请求,订阅通道数: {}", argsArray.size()); |
| | | // } catch (Exception e) { |
| | | // log.error("发送订阅请求失败", e); |
| | | // } |
| | | // } |
| | | // |
| | | // private void handleWebSocketMessage(String message) { |
| | | // try { |
| | | // JSONObject response = JSON.parseObject(message); |
| | | // String event = response.getString("event"); |
| | | // |
| | | // if ("subscribe".equals(event)) { |
| | | // log.info("订阅成功: {}", response.getJSONObject("arg")); |
| | | // } else if ("error".equals(event)) { |
| | | // log.error("订阅错误: code={}, msg={}", |
| | | // response.getString("code"), response.getString("msg")); |
| | | // } else if ("pong".equals(event)) { |
| | | // log.debug("收到pong响应"); |
| | | // cancelPongTimeout(); |
| | | // } else { |
| | | // // 处理推送数据 |
| | | // processPushData(response); |
| | | // } |
| | | // } catch (Exception e) { |
| | | // log.error("处理WebSocket消息失败: {}", message, e); |
| | | // } |
| | | // } |
| | | // |
| | | // private void processPushData(JSONObject response) { |
| | | // try { |
| | | // JSONArray dataArray = response.getJSONArray("data"); |
| | | // if (dataArray != null && !dataArray.isEmpty()) { |
| | | // JSONObject arg = response.getJSONObject("arg"); |
| | | // String channel = arg.getString("channel"); |
| | | // String instId = arg.getString("instId"); |
| | | // |
| | | // // 解析K线周期 |
| | | // String period = extractPeriodFromChannel(channel); |
| | | // |
| | | // // 处理每条K线数据 |
| | | // for (int i = 0; i < dataArray.size(); i++) { |
| | | // JSONArray klineData = dataArray.getJSONArray(i); |
| | | // updateKlineData(instId, period, klineData); |
| | | // } |
| | | // } |
| | | // } catch (Exception e) { |
| | | // log.error("处理推送数据失败", e); |
| | | // } |
| | | // } |
| | | // |
| | | // private String extractPeriodFromChannel(String channel) { |
| | | // // 从channel名称中提取周期标识 |
| | | // if (channel.startsWith("mark-price-candle")) { |
| | | // return channel.replace("mark-price-candle", ""); |
| | | // } |
| | | // return "1m"; // 默认1分钟 |
| | | // } |
| | | // |
| | | // private void updateKlineData(String instId, String period, JSONArray klineData) { |
| | | // try { |
| | | // String timestamp = klineData.getString(0); |
| | | // String open = klineData.getString(1); |
| | | // String high = klineData.getString(2); |
| | | // String low = klineData.getString(3); |
| | | // String close = klineData.getString(4); |
| | | // String confirm = klineData.getString(5); // 0=未完结, 1=已完结 |
| | | // |
| | | // // 构造Redis键 |
| | | // String redisKey = "KINE_" + instId.replace("-", "") + "_" + period; |
| | | // |
| | | // // 创建K线对象并存储到Redis |
| | | // Map<String, Object> klineMap = new HashMap<>(); |
| | | // klineMap.put("ts", timestamp); |
| | | // klineMap.put("o", open); |
| | | // klineMap.put("h", high); |
| | | // klineMap.put("l", low); |
| | | // klineMap.put("c", close); |
| | | // klineMap.put("confirm", confirm); |
| | | // |
| | | // // 如果K线已完结,则更新Redis数据 |
| | | // if ("1".equals(confirm)) { |
| | | //// redisUtils.set(redisKey, klineMap); |
| | | // log.debug("更新K线数据: {} -> {}", redisKey, klineMap); |
| | | // } |
| | | // |
| | | // } catch (Exception e) { |
| | | // log.error("更新K线数据失败: instId={}, period={}", instId, period, e); |
| | | // } |
| | | // } |
| | | // |
| | | // private synchronized void startHeartbeat() { |
| | | // if (heartbeatExecutor != null) { |
| | | // heartbeatExecutor.shutdown(); |
| | | // try { |
| | | // // 等待现有任务完成,最多等待5秒 |
| | | // if (!heartbeatExecutor.awaitTermination(5, TimeUnit.SECONDS)) { |
| | | // heartbeatExecutor.shutdownNow(); |
| | | // } |
| | | // } catch (InterruptedException e) { |
| | | // heartbeatExecutor.shutdownNow(); |
| | | // Thread.currentThread().interrupt(); |
| | | // } |
| | | // } |
| | | // |
| | | // heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> { |
| | | // Thread thread = new Thread(r, "okx-websocket-heartbeat"); |
| | | // thread.setDaemon(true); |
| | | // return thread; |
| | | // }); |
| | | // |
| | | // // 定期发送ping消息 |
| | | // heartbeatExecutor.scheduleWithFixedDelay(this::checkConnectionAndPing, |
| | | // HEARTBEAT_INTERVAL, HEARTBEAT_INTERVAL, TimeUnit.SECONDS); |
| | | // } |
| | | // |
| | | // /** |
| | | // * 检查连接状态并在需要时发送ping |
| | | // */ |
| | | // private void checkConnectionAndPing() { |
| | | // try { |
| | | // // 检查连接是否仍然有效 |
| | | // if (webSocketClient == null || !webSocketClient.isOpen()) { |
| | | // log.warn("WebSocket连接已断开,准备重连"); |
| | | // scheduleReconnect(); |
| | | // return; |
| | | // } |
| | | // |
| | | // // 检查上次消息时间,如果太久没有收到消息则发送ping |
| | | // long now = System.currentTimeMillis(); |
| | | // long lastTime = lastMessageTime.get(); |
| | | // if (now - lastTime > HEARTBEAT_INTERVAL * 1000L) { |
| | | // sendPing(); |
| | | // } |
| | | // } catch (Exception e) { |
| | | // log.error("检查连接状态时发生异常", e); |
| | | // } |
| | | // } |
| | | // |
| | | // private void sendPing() { |
| | | // try { |
| | | // if (webSocketClient != null && webSocketClient.isOpen()) { |
| | | // JSONObject ping = new JSONObject(); |
| | | // ping.put("op", "ping"); |
| | | // webSocketClient.send(ping.toJSONString()); |
| | | // log.debug("发送ping请求"); |
| | | // |
| | | // // 设置pong超时检查 |
| | | // schedulePongTimeout(); |
| | | // } |
| | | // } catch (Exception e) { |
| | | // log.warn("发送ping失败", e); |
| | | // // 发送失败时安排重连 |
| | | // scheduleReconnect(); |
| | | // } |
| | | // } |
| | | // |
| | | // private void schedulePongTimeout() { |
| | | // if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) { |
| | | // pongTimeoutFuture.cancel(true); |
| | | // } |
| | | // |
| | | // if (heartbeatExecutor != null) { |
| | | // pongTimeoutFuture = heartbeatExecutor.schedule(() -> { |
| | | // log.warn("未收到pong响应,准备重新连接"); |
| | | // scheduleReconnect(); |
| | | // }, PONG_TIMEOUT, TimeUnit.SECONDS); |
| | | // } |
| | | // } |
| | | // |
| | | // private void cancelPongTimeout() { |
| | | // if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) { |
| | | // pongTimeoutFuture.cancel(true); |
| | | // } |
| | | // } |
| | | // |
| | | // /** |
| | | // * 在独立线程中安排重连,避免在WebSocket线程中直接重连 |
| | | // */ |
| | | // private void scheduleReconnect() { |
| | | // // 使用守护线程执行重连 |
| | | // Thread reconnectThread = new Thread(() -> { |
| | | // try { |
| | | // Thread.sleep(5000); // 等待5秒后重连 |
| | | // reconnect(); |
| | | // } catch (InterruptedException e) { |
| | | // Thread.currentThread().interrupt(); |
| | | // log.warn("重连任务被中断"); |
| | | // } catch (Exception e) { |
| | | // log.error("重连过程中发生异常", e); |
| | | // } |
| | | // }, "okx-kline-scheduled-reconnect"); |
| | | // reconnectThread.setDaemon(true); |
| | | // reconnectThread.start(); |
| | | // } |
| | | // |
| | | // private void reconnect() { |
| | | // try { |
| | | // log.info("开始重新连接..."); |
| | | // // 先清理旧的连接 |
| | | // if (webSocketClient != null) { |
| | | // try { |
| | | // webSocketClient.closeBlocking(); |
| | | // } catch (Exception e) { |
| | | // log.warn("关闭旧连接时发生异常", e); |
| | | // } |
| | | // } |
| | | // |
| | | // // 建立新连接 |
| | | // connect(); |
| | | // } catch (Exception e) { |
| | | // log.error("重连过程中发生异常", e); |
| | | // } |
| | | // } |
| | | //} |