解决server sdk有内存泄漏的问题

This commit is contained in:
heavyrian2012
2026-01-20 10:30:28 +08:00
parent 51dd94d3a7
commit 44a916892b
5 changed files with 267 additions and 260 deletions
@@ -196,4 +196,16 @@ public class InputOutputUserInfo {
public void setDeleted(int deleted) {
this.deleted = deleted;
}
@Override
public String toString() {
return "{" +
"userId='" + userId + '\'' +
", name='" + name + '\'' +
", displayName='" + displayName + '\'' +
", portrait='" + portrait + '\'' +
", mobile='" + mobile + '\'' +
", updateDt=" + updateDt +
'}';
}
}
@@ -1,195 +1,135 @@
package cn.wildfirechat.sdk.utilities;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.sdk.model.IMResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import ikidou.reflect.TypeBuilder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;
public class AdminHttpUtils extends JsonUtils {
public class AdminHttpUtils extends HttpUtils {
// ======================== 常量定义(消除硬编码)========================
private static final Logger LOG = LoggerFactory.getLogger(AdminHttpUtils.class);
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private static String adminUrl;
private static String adminSecret;
private static CloseableHttpClient httpClient;
// 连接池配置常量
private static final int DEFAULT_CONNECT_TIMEOUT = 15000;
private static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 3000;
private static final int DEFAULT_SOCKET_TIMEOUT = 15000;
private static final int MAX_CONN_TOTAL = 100;
private static final int MAX_CONN_PER_ROUTE = 50;
private static final long IDLE_CONNECTION_EVICT_TIME = 60L;
private static final int VALIDATE_AFTER_INACTIVITY = 1000;
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final int NONCE_MAX_RANGE = 1000000;
// ======================== 线程安全的全局变量 ========================
private static volatile String adminUrl;
private static volatile String adminSecret;
private static volatile CloseableHttpClient httpClient;
// ======================== 初始化方法 ========================
public static void init(String url, String secret) {
init(url, secret, 15000);
init(url, secret, DEFAULT_SOCKET_TIMEOUT);
}
/**
* 初始化HTTP客户端和配置
* @param url IM服务管理地址
* @param secret 管理密钥
* @param timeout 套接字超时时间(毫秒)
*/
public static synchronized void init(String url, String secret, int timeout) {
// 参数校验
if (isNullOrEmpty(url) || isNullOrEmpty(secret)) {
throw new IllegalArgumentException("IM服务地址或密钥不能为空");
}
adminUrl = url.trim();
adminSecret = secret.trim();
if(httpClient == null) {
// 若已存在HttpClient,先关闭再重新初始化(支持配置更新)
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
LOG.error("关闭旧HttpClient连接池失败", e);
}
}
// 初始化连接池
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setValidateAfterInactivity(1000);
int connectTimeout = 15000; // 连接超时时间
int connectionRequestTimeout = 3000; // 从连接池获取连接的超时时间
cm.setValidateAfterInactivity(VALIDATE_AFTER_INACTIVITY);
// 构建请求配置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
.setSocketTimeout(timeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
.build();
// 构建HttpClient
httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.evictExpiredConnections()
.evictIdleConnections(60L, TimeUnit.SECONDS)
.setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE)
.setMaxConnTotal(100)
.setMaxConnPerRoute(50)
.evictIdleConnections(IDLE_CONNECTION_EVICT_TIME, TimeUnit.SECONDS)
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)) // 重试3次,不重试IO异常
.setMaxConnTotal(MAX_CONN_TOTAL)
.setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
.build();
}
LOG.info("AdminHttpUtils初始化完成,IM服务地址:{}", adminUrl);
}
// ======================== HTTP GET请求 ========================
public static <T> IMResult<T> httpGet(String path, Class<T> clazz) throws Exception {
if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret)) {
LOG.error("野火IM Server SDK必须先初始化才能使用,是不是忘记初始化了!请调用AdminConfig.initAdmin(AdminUrl, AdminSecret);进行初始化");
throw new Exception("SDK没有初始化,请调用AdminConfig.initAdmin(AdminUrl, AdminSecret);进行初始化");
}
// 前置校验
validateInitStatus(adminUrl, adminSecret, httpClient);
if (isNullOrEmpty(path)) {
throw new Exception("路径缺失");
throw new IllegalArgumentException("请求路径不能为空");
}
HttpGet get = null;
HttpGet httpGet = new HttpGet(adminUrl + path);
try {
get = new HttpGet(adminUrl + path);
HttpResponse response = httpClient.execute(get);
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
if (response.getEntity().getContentLength() > 0) {
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
StringBuilder sb = new StringBuilder();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line).append(NL);
}
in.close();
content = sb.toString();
LOG.info("http request response content: {}", content);
}
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: " + statusCode + " error msg:" + content);
throw new Exception("Http request error with code:" + statusCode);
} else {
return fromJsonObject(content, clazz);
}
HttpResponse response = httpClient.execute(httpGet);
return handleResponse(response, clazz, adminUrl, adminSecret);
} catch (Exception e) {
e.printStackTrace();
throw e;
LOG.error("HTTP GET请求失败,路径:{}", path, e);
throw new Exception("HTTP GET请求异常:" + e.getMessage(), e);
} finally {
if(get != null) {
get.releaseConnection();
}
httpGet.releaseConnection();
}
}
// ======================== HTTP JSON POST请求 ========================
public static <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception {
if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret)) {
LOG.error("野火IM Server SDK必须先初始化才能使用,是不是忘记初始化了!请调用AdminConfig.initAdmin(AdminUrl, AdminSecret);进行初始化");
throw new Exception("SDK没有初始化,请调用AdminConfig.initAdmin(AdminUrl, AdminSecret);进行初始化");
}
if (isNullOrEmpty(path)) {
throw new Exception("路径缺失");
}
String url = adminUrl + path;
HttpPost post = null;
try {
int nonce = (int)(Math.random() * 100000 + 3);
return httpJsonPost(adminUrl, adminSecret, httpClient, path, object, clazz, httpPost -> {
// 构建签名头
int nonce = SECURE_RANDOM.nextInt(NONCE_MAX_RANGE) + 1; // 安全随机数
long timestamp = System.currentTimeMillis();
String str = nonce + "|" + adminSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(str);
String signStr = nonce + "|" + adminSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(signStr);
post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
post.setHeader("nonce", nonce + "");
post.setHeader("timestamp", "" + timestamp);
post.setHeader("sign", sign);
String jsonStr = "";
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request:{} content: {}", url, jsonStr);
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
if (response.getEntity().getContentLength() > 0) {
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
StringBuilder sb = new StringBuilder();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line).append(NL);
}
in.close();
content = sb.toString();
LOG.info("http request response content: {}", content);
}
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: " + statusCode + " error msg:" + content);
throw new Exception("Http request error with code:" + statusCode);
} else {
IMResult<T> result = fromJsonObject(content, clazz);
if(result != null){
if(result.getErrorCode() == ErrorCode.ERROR_CODE_AUTH_FAILURE) {
LOG.error("鉴权失败,IM服务地址或者密钥配置错误,请检查IM服务{}的配置文件中的http.admin.secret_key是否是{}", adminUrl, adminSecret);
} else if(result.getErrorCode() == ErrorCode.ERROR_CODE_SIGN_EXPIRED) {
LOG.error("时间验证失败,请确保当前服务和IM服务{}的时间是一致的", adminUrl);
}
}
return result;
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if(post != null) {
post.releaseConnection();
}
}
// 设置请求头
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("nonce", String.valueOf(nonce));
httpPost.setHeader("timestamp", String.valueOf(timestamp));
httpPost.setHeader("sign", sign);
});
}
}
@@ -30,9 +30,8 @@ import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class ChannelHttpUtils extends JsonUtils implements Closeable {
public class ChannelHttpUtils extends HttpUtils implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(ChannelHttpUtils.class);
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private String imurl;
private String channelId;
@@ -88,71 +87,19 @@ public class ChannelHttpUtils extends JsonUtils implements Closeable {
}
public <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{
if (isNullOrEmpty(imurl) || isNullOrEmpty(path)) {
LOG.error("Not init IM SDK correctly. Do you forget init it?");
throw new Exception("SDK url or secret lack!");
}
String url = imurl + path;
HttpPost post = null;
try {
return httpJsonPost(imurl, channelId, httpClient, path, object, clazz, post -> {
int nonce = (int)(Math.random() * 100000 + 3);
long timestamp = System.currentTimeMillis();
String str = nonce + "|" + channelSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(str);
post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
post.setHeader("nonce", nonce + "");
post.setHeader("timestamp", "" + timestamp);
post.setHeader("cid", channelId);
post.setHeader("sign", sign);
String jsonStr = "";
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request:{} content: {}", url, jsonStr);
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: "+statusCode);
throw new Exception("Http request error with code:" + statusCode);
}else{
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String content = sb.toString();
LOG.info("http request response content: {}", content);
return fromJsonObject(content, clazz);
}
} catch (Exception e) {
checkPort();
e.printStackTrace();
throw e;
}finally{
if(post != null){
post.releaseConnection();
}
}
});
}
public String getChannelId() {
@@ -0,0 +1,161 @@
package cn.wildfirechat.sdk.utilities;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.sdk.model.IMResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;
public class HttpUtils extends JsonUtils {
// ======================== 常量定义(消除硬编码)========================
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
public static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create();
public static interface HeaderCallback {
public void addHeaders(HttpPost httpPost);
}
// ======================== HTTP JSON POST请求 ========================
public static <T> IMResult<T> httpJsonPost(String adminUrl, String adminSecret, HttpClient httpClient, String path, Object object, Class<T> clazz, HeaderCallback headerCallback) throws Exception {
// 前置校验
validateInitStatus(adminUrl, adminSecret, httpClient);
if (isNullOrEmpty(path)) {
throw new IllegalArgumentException("请求路径不能为空");
}
String url = adminUrl + path;
HttpPost httpPost = new HttpPost(url);
try {
headerCallback.addHeaders(httpPost);
// 设置请求体
String jsonStr = object == null ? "" : GSON.toJson(object);
LOG.info("HTTP POST请求:{},请求体:{}", url, truncateLogContent(jsonStr));
StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8);
entity.setContentEncoding(StandardCharsets.UTF_8.name());
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 执行请求并处理响应
HttpResponse response = httpClient.execute(httpPost);
return handleResponse(response, clazz, adminUrl, adminSecret);
} catch (Exception e) {
LOG.error("HTTP POST请求失败,路径:{}", path, e);
throw new Exception("HTTP POST请求异常:" + e.getMessage(), e);
} finally {
httpPost.releaseConnection();
}
}
// ======================== 私有工具方法 ========================
/**
* 校验初始化状态
*/
protected static void validateInitStatus(String adminUrl, String adminSecret, HttpClient httpClient) {
if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret) || httpClient == null) {
String errorMsg = "野火IM Server SDK未初始化,请调用AdminConfig.initAdmin(AdminUrl, AdminSecret)完成初始化";
LOG.error(errorMsg);
throw new IllegalStateException(errorMsg);
}
}
/**
* 处理HTTP响应,统一解析逻辑
*/
protected static <T> IMResult<T> handleResponse(HttpResponse response, Class<T> clazz, String adminUrl, String adminSecret) throws Exception {
int statusCode = response.getStatusLine().getStatusCode();
String content = readResponseContent(response);
// 非200状态码处理
if (statusCode != HttpStatus.SC_OK) {
String errorMsg = String.format("HTTP请求失败,状态码:%d,响应内容:%s", statusCode, truncateLogContent(content));
LOG.error(errorMsg);
throw new Exception(errorMsg);
}
// 解析响应体
IMResult<T> result = fromJsonObject(content, clazz);
if (result != null) {
if (result.getErrorCode() == ErrorCode.ERROR_CODE_AUTH_FAILURE) {
LOG.error("鉴权失败,请检查IM服务地址({})或密钥({})配置", adminUrl, maskSecret(adminSecret));
} else if (result.getErrorCode() == ErrorCode.ERROR_CODE_SIGN_EXPIRED) {
LOG.error("签名过期,请确保当前服务与IM服务({})时间同步", adminUrl);
}
}
return result;
}
/**
* 读取响应体(兼容分块传输,修复getContentLength=-1问题)
*/
protected static String readResponseContent(HttpResponse response) throws IOException {
if (response.getEntity() == null) {
return "";
}
// 使用try-with-resources自动关闭所有流,避免资源泄漏
try (InputStream is = response.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)) {
StringBuilder sb = new StringBuilder();
String line;
String nl = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
sb.append(line).append(nl);
}
String content = sb.toString().trim();
LOG.info("HTTP响应内容:{}", truncateLogContent(content));
return content;
}
}
/**
* 截断超长日志内容(避免日志爆炸)
*/
protected static String truncateLogContent(String content) {
if (content == null) {
return "";
}
int maxLength = 1024;
return content.length() > maxLength ? content.substring(0, maxLength) + "..." : content;
}
/**
* 掩码处理密钥(避免日志泄露敏感信息)
*/
protected static String maskSecret(String secret) {
if (isNullOrEmpty(secret) || secret.length() <= 4) {
return "******";
}
return secret.substring(0, 2) + "******" + secret.substring(secret.length() - 2);
}
/**
* 空值判断(补充实现,避免依赖外部未定义方法)
*/
public static boolean isNullOrEmpty(String str) {
return str == null || str.trim().isEmpty();
}
}
@@ -31,7 +31,7 @@ import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class RobotHttpUtils extends JsonUtils implements Closeable {
public class RobotHttpUtils extends HttpUtils implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(RobotHttpUtils.class);
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
@@ -90,72 +90,19 @@ public class RobotHttpUtils extends JsonUtils implements Closeable {
public <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{
if (isNullOrEmpty(url) || isNullOrEmpty(path)) {
LOG.error("Not init IM SDK correctly. Do you forget init it?");
throw new Exception("SDK url or secret lack!");
}
String url = this.url + path;
HttpPost post = null;
try {
return httpJsonPost(url, robotId, httpClient, path, object, clazz, post -> {
int nonce = (int)(Math.random() * 100000 + 3);
long timestamp = System.currentTimeMillis();
String str = nonce + "|" + robotSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(str);
post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
post.setHeader("nonce", nonce + "");
post.setHeader("timestamp", "" + timestamp);
post.setHeader("rid", robotId);
post.setHeader("sign", sign);
String jsonStr = null;
if (object != null) {
jsonStr = gson.toJson(object);
}
LOG.info("http request:{} content: {}", url, jsonStr);
if(!StringUtil.isNullOrEmpty(jsonStr)) {
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
}
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: "+statusCode);
throw new Exception("Http request error with code:" + statusCode);
}else{
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String content = sb.toString();
LOG.info("http request response content: {}", content);
return fromJsonObject(content, clazz);
}
} catch (Exception e) {
checkPort();
e.printStackTrace();
throw e;
}finally{
if(post != null){
post.releaseConnection();
}
}
});
}
public String getRobotId() {