From 5516e36f3ec2fa09803c427051e3887701032843 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Wed, 13 May 2026 16:46:14 +0800
Subject: [PATCH] refactor(okxNewPrice): 账户配置
---
/dev/null | 352 ----------------------------------------------------------
1 files changed, 0 insertions(+), 352 deletions(-)
diff --git a/src/main/java/com/xcong/excoin/modules/newPrice/OkxNewPriceWebSocketClient.java b/src/main/java/com/xcong/excoin/modules/newPrice/OkxNewPriceWebSocketClient.java
deleted file mode 100644
index 27b97d9..0000000
--- a/src/main/java/com/xcong/excoin/modules/newPrice/OkxNewPriceWebSocketClient.java
+++ /dev/null
@@ -1,321 +0,0 @@
-package com.xcong.excoin.modules.newPrice;
-
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.CoinEnums;
-import com.xcong.excoin.modules.okxNewPrice.utils.SSLConfig;
-import com.xcong.excoin.rabbit.pricequeue.WebsocketPriceService;
-import com.xcong.excoin.utils.CoinTypeConvert;
-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.boot.autoconfigure.condition.ConditionalOnProperty;
-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.util.concurrent.*;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * OKX 新价格 WebSocket 客户端类,用于连接 OKX 的 WebSocket 接口,
- * 实时获取并处理标记价格(mark price)数据,并将价格信息存储到 Redis 中。
- * 同时支持心跳检测、自动重连以及异常恢复机制。
- * @author Administrator
- */
-@Slf4j
-@Component
-@ConditionalOnProperty(prefix = "app", name = "websocket", havingValue = "true")
-public class OkxNewPriceWebSocketClient {
- @Resource
- private WebsocketPriceService websocketPriceService;
- @Resource
- private RedisUtils redisUtils;
-
- private WebSocketClient webSocketClient;
- private ScheduledExecutorService heartbeatExecutor;
- private volatile ScheduledFuture<?> pongTimeoutFuture;
- private final AtomicReference<Long> lastMessageTime = new AtomicReference<>(System.currentTimeMillis());
-
- private static final String CHANNEL = "mark-price";
-
- // 心跳超时时间(秒),小于30秒
- private static final int HEARTBEAT_TIMEOUT = 10;
-
- // 共享线程池用于重连等异步任务
- private final ExecutorService sharedExecutor = Executors.newCachedThreadPool(r -> {
- Thread t = new Thread(r, "okx-ws-shared-worker");
- t.setDaemon(true);
- return t;
- });
-
- /**
- * 初始化方法,在 Spring Bean 构造完成后执行。
- * 负责建立 WebSocket 连接并启动心跳检测任务。
- */
- @PostConstruct
- public void init() {
- connect();
- startHeartbeat();
- }
-
- /**
- * 销毁方法,在 Spring Bean 销毁前执行。
- * 关闭 WebSocket 连接、停止心跳定时器及相关的线程资源。
- */
- @PreDestroy
- public void destroy() {
- if (webSocketClient != null && webSocketClient.isOpen()) {
- webSocketClient.close();
- }
- if (heartbeatExecutor != null) {
- heartbeatExecutor.shutdownNow();
- }
- if (pongTimeoutFuture != null) {
- pongTimeoutFuture.cancel(true);
- }
- sharedExecutor.shutdownNow();
- }
- private static final String WS_URL_MONIPAN = "wss://wspap.okx.com:8443/ws/v5/public";
- private static final String WS_URL_SHIPAN = "wss://ws.okx.com:8443/ws/v5/public";
- private static final boolean isAccountType = false;
-
- /**
- * 建立与 OKX WebSocket 服务器的连接。
- * 设置回调函数以监听连接打开、接收消息、关闭和错误事件。
- */
- private void connect() {
- try {
- SSLConfig.configureSSL();
- System.setProperty("https.protocols", "TLSv1.2,TLSv1.3");
- String WS_URL = WS_URL_MONIPAN;
- if (isAccountType){
- WS_URL = WS_URL_SHIPAN;
- }
- URI uri = new URI(WS_URL);
- webSocketClient = new WebSocketClient(uri) {
- @Override
- public void onOpen(ServerHandshake handshake) {
- log.info("OKX New Price WebSocket连接成功");
- resetHeartbeatTimer();
- subscribeChannels();
- }
-
- @Override
- public void onMessage(String message) {
- lastMessageTime.set(System.currentTimeMillis());
- handleWebSocketMessage(message);
- resetHeartbeatTimer();
- }
-
- @Override
- public void onClose(int code, String reason, boolean remote) {
- log.warn("OKX New Price WebSocket连接关闭: code={}, reason={}", code, reason);
- cancelPongTimeout();
-
- sharedExecutor.execute(() -> {
- try {
- reconnectWithBackoff();
- } catch (InterruptedException ignored) {
- Thread.currentThread().interrupt();
- } catch (Exception e) {
- log.error("重连失败", e);
- }
- });
- }
-
- @Override
- public void onError(Exception ex) {
- log.error("OKX New Price WebSocket发生错误", ex);
- }
- };
-
- webSocketClient.connect();
- } catch (URISyntaxException e) {
- log.error("WebSocket URI格式错误", e);
- }
- }
-
- /**
- * 订阅指定交易对的价格通道。
- * 构造订阅请求并发送给服务端。
- */
- private void subscribeChannels() {
- JSONObject subscribeMsg = new JSONObject();
- subscribeMsg.put("op", "subscribe");
-
- JSONArray argsArray = new JSONArray();
- JSONObject arg = new JSONObject();
- arg.put("channel", CHANNEL);
- arg.put("instId", CoinEnums.HE_YUE.getCode());
- argsArray.add(arg);
-
- subscribeMsg.put("args", argsArray);
- webSocketClient.send(subscribeMsg.toJSONString());
- log.info("已发送价格订阅请求,订阅通道数: {}", argsArray.size());
- }
-
- /**
- * 处理从 WebSocket 收到的消息。
- * 包括订阅确认、错误响应、心跳响应以及实际的数据推送。
- *
- * @param message 来自 WebSocket 的原始字符串消息
- */
- 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);
- }
- }
-
- /**
- * 解析并处理价格推送数据。
- * 将最新的标记价格存入 Redis 并触发后续业务逻辑比较处理。
- *
- * @param response 包含价格数据的 JSON 对象
- */
- private void processPushData(JSONObject response) {
- try {
- JSONArray dataArray = response.getJSONArray("data");
- if (dataArray != null && !dataArray.isEmpty()) {
- for (int i = 0; i < dataArray.size(); i++) {
- try {
- JSONObject priceData = dataArray.getJSONObject(i);
- String instId = priceData.getString("instId");
- String markPx = priceData.getString("markPx");
- String ts = priceData.getString("ts");
-
- redisUtils.set(CoinEnums.HE_YUE.getCode(), markPx);
-
- log.debug("更新最新价格: {} = {}, 币种: {}", CoinEnums.HE_YUE.getCode(), markPx, instId);
- } catch (Exception innerEx) {
- log.warn("处理单条价格数据失败", innerEx);
- }
- }
- }
- } catch (Exception e) {
- log.error("处理价格推送数据失败", e);
- }
- }
-
- /**
- * 构建 Redis Key
- */
- private String buildRedisKey(String instId) {
- return "PRICE_" + instId.replace("-", "");
- }
-
- /**
- * 启动心跳检测任务。
- * 使用 ScheduledExecutorService 定期检查是否需要发送 ping 请求来维持连接。
- */
- private void startHeartbeat() {
- if (heartbeatExecutor != null) {
- heartbeatExecutor.shutdownNow();
- }
-
- heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
- Thread t = new Thread(r, "okx-newprice-heartbeat");
- t.setDaemon(true);
- return t;
- });
-
- heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout, 25, 25, TimeUnit.SECONDS);
- }
-
- /**
- * 重置心跳计时器。
- * 当收到新消息或发送 ping 后取消当前超时任务并重新安排下一次超时检查。
- */
- private synchronized void resetHeartbeatTimer() {
- cancelPongTimeout();
-
- if (heartbeatExecutor != null) {
- pongTimeoutFuture = heartbeatExecutor.schedule(this::checkHeartbeatTimeout,
- HEARTBEAT_TIMEOUT, TimeUnit.SECONDS);
- }
- }
-
- /**
- * 检查心跳超时情况。
- * 若长时间未收到任何消息则主动发送 ping 请求保持连接活跃。
- */
- private void checkHeartbeatTimeout() {
- long currentTime = System.currentTimeMillis();
- long lastTime = lastMessageTime.get();
-
- if (currentTime - lastTime >= HEARTBEAT_TIMEOUT * 1000L) {
- sendPing();
- }
- }
-
- /**
- * 发送 ping 请求至 WebSocket 服务端。
- * 用于维持长连接有效性。
- */
- private void sendPing() {
- try {
- if (webSocketClient != null && webSocketClient.isOpen()) {
- JSONObject ping = new JSONObject();
- ping.put("op", "ping");
- webSocketClient.send(ping.toJSONString());
- log.debug("发送ping请求");
- }
- } catch (Exception e) {
- log.warn("发送ping失败", e);
- }
- }
-
- /**
- * 取消当前的心跳超时任务。
- * 在收到 pong 或其他有效消息时调用此方法避免不必要的断开重连。
- */
- private synchronized void cancelPongTimeout() {
- if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) {
- pongTimeoutFuture.cancel(true);
- }
- }
-
- /**
- * 执行 WebSocket 重连操作。
- * 在连接意外中断后尝试重新建立连接。
- */
- private void reconnectWithBackoff() throws InterruptedException {
- int attempt = 0;
- int maxAttempts = 3;
- long delayMs = 5000;
-
- while (attempt < maxAttempts) {
- try {
- Thread.sleep(delayMs);
- connect();
- return;
- } catch (Exception e) {
- log.warn("第{}次重连失败", attempt + 1, e);
- delayMs *= 2;
- attempt++;
- }
- }
-
- log.error("超过最大重试次数({})仍未连接成功", maxAttempts);
- }
-}
diff --git a/src/main/java/com/xcong/excoin/modules/newPrice/OkxWebSocketClient.java b/src/main/java/com/xcong/excoin/modules/newPrice/OkxWebSocketClient.java
deleted file mode 100644
index a7aa6d9..0000000
--- a/src/main/java/com/xcong/excoin/modules/newPrice/OkxWebSocketClient.java
+++ /dev/null
@@ -1,352 +0,0 @@
-//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);
-// }
-// }
-//}
\ No newline at end of file
--
Gitblit v1.9.1