package com.xcong.excoin.modules.gateApi;
|
|
import io.gate.gateapi.ApiClient;
|
import io.gate.gateapi.ApiException;
|
import io.gate.gateapi.ApiResponse;
|
import okhttp3.Call;
|
import okhttp3.Response;
|
|
import java.io.IOException;
|
import java.lang.reflect.Type;
|
|
/**
|
* 修复 gate-api SDK 同步请求 Response 未关闭导致 OkHttp 连接泄漏的 ApiClient 子类。
|
*
|
* <p>SDK 的 {@code ApiClient.execute(Call, Type)} 读取响应体后不调用 {@code response.close()},
|
* 触发 OkHttp 连接池 "A connection to ... was leaked. Did you forget to close a response body?" 告警
|
* (日志中已多次出现)。本类用 try-with-resources 保证响应在任意路径
|
* (成功 / 4xx / 反序列化失败 / IO 异常)都被关闭,行为与 SDK 内置执行完全一致
|
* ({@code handleResponse} 为 SDK 公开方法)。</p>
|
*/
|
public class GateClosingApiClient extends ApiClient {
|
|
/** 连接超时(毫秒) */
|
private static final int CONNECT_TIMEOUT_MS = 10_000;
|
/** 读超时(毫秒):覆盖 REST 查询挂起的最长等待时间 */
|
private static final int READ_TIMEOUT_MS = 30_000;
|
/** 写超时(毫秒) */
|
private static final int WRITE_TIMEOUT_MS = 30_000;
|
|
public GateClosingApiClient() {
|
super();
|
// 设置超时,避免某个 REST 请求永久阻塞,进而拖死单线程交易执行器
|
setConnectTimeout(CONNECT_TIMEOUT_MS);
|
setReadTimeout(READ_TIMEOUT_MS);
|
setWriteTimeout(WRITE_TIMEOUT_MS);
|
}
|
|
/**
|
* 重写 SDK 执行逻辑:响应读取完成后强制 close。
|
* <ul>
|
* <li>成功路径:反序列化后关闭;</li>
|
* <li>异常路径(handleResponse 抛 ApiException / IOException):try-with-resources 兜底关闭。</li>
|
* </ul>
|
*/
|
@Override
|
public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
|
try (Response response = call.execute()) {
|
T data = handleResponse(response, returnType);
|
return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
|
} catch (IOException e) {
|
throw new ApiException(e);
|
}
|
}
|
}
|