1
zj
2024-08-07 8ed60795a7c278f9699616f72eb05ce49800ba6f
bitgetsClient/src/main/java/org/example/bitgetsclient/WsBean/BitgetsWsBean.java
@@ -4,12 +4,15 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.bitgetsclient.BitgetsClientApplication;
import org.example.bitgetsclient.pojo.Currency;
import org.example.bitgetsclient.server.impl.CurrencySerivceImpl;
import org.example.bitgetsclient.wsClient.BitgetClient;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@@ -19,6 +22,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
@@ -32,6 +36,9 @@
    @Autowired
    private CurrencySerivceImpl currencyService;
    @Autowired
    private ConfigurableApplicationContext context;
    @Autowired
    @Qualifier("threadPoolTaskExecutor")
@@ -51,12 +58,41 @@
                int toIndex = Math.min(fromIndex + batchSize, totalSize); // 计算结束索引
                List<Currency> sublist = mexc.subList(fromIndex, toIndex); // 切分子列表
                String parameter = getParameter(sublist); // 获取参数
                // 使用自定义线程池提交任务
                threadPoolTaskExecutor.execute(new BitgetClient(parameter)::start); // 提交到线程池执行
                threadPoolTaskExecutor.execute(() -> {
                    try {
                        new BitgetClient(parameter).start();
                    } catch (Exception e) {
                        run();
                    }
                });
            }
        }
    }
    private boolean runExecuted = false;
    private synchronized void run() {
        if (runExecuted) {
            return; // 已经执行过,直接返回
        }
        runExecuted = true;
        log.info("ws 异常开始重启");
        Thread restartThread = new Thread(() -> {
            try {
                SpringApplication.exit(context, () -> 0);
                SpringApplication.run(BitgetsClientApplication.class);
                log.info("ws 重启成功");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("ws 重启失败");
            }
        });
        restartThread.setDaemon(false);
        restartThread.start();
        log.info("ws 重启失败");
    }
    public String getParameter(List<Currency> list) throws JsonProcessingException, JSONException {
        // 创建一个ObjectMapper实例
        ObjectMapper mapper = new ObjectMapper();