以下是配置HttpClient代码
private static CloseableHttpClient init() {
try {
PrivateKey privateKey = PemUtil.loadPrivateKey(
new ByteArrayInputStream(merchantPrivateKey.getBytes(StandardCharsets.UTF_8)));
CertificatesManager certificatesManager = CertificatesManager.getInstance();
certificatesManager.putMerchant(merchantId, new WechatPay2Credentials(merchantId,
new PrivateKeySigner(merchantSerialNumber, privateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8));
verifier = certificatesManager.getVerifier(merchantId);
//...
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(merchantId, merchantSerialNumber, privateKey)
.withValidator(new WechatPay2Validator(verifier))
.evictExpiredConnections() // 开启回收空闲线程
.evictIdleConnections(3L, TimeUnit.SECONDS) // 30秒回收空闲连接
.setMaxConnPerRoute(300).setMaxConnTotal(1000)
.build();
return httpClient;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
以下是调用api接口代码
private static <T extends WechatBaseResponse> T execute(String url, Object params, boolean isPost, Class<T> tClass) {
long startTime = System.currentTimeMillis();
String message = JsonUtils.toJsonString(params);
T t = null;
try {
HttpUriRequest request;
if (isPost) {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(JsonUtils.toJsonString(params), "utf-8"));
request = httpPost;
} else {
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", "application/json");
request = httpGet;
}
CloseableHttpResponse response = httpClient.execute(request);
String result = EntityUtils.toString(response.getEntity());
t = JsonUtils.parseObject(result, tClass);
logger.info("【微信】请求 url={} 请求参数={} 响应数据={} 处理时间={}ms", url, message, result, System.currentTimeMillis() - startTime);
} catch (IOException e) {
logger.error("【微信】调用异常 url={} 请求参数={}", url, message, e);
try {
t = tClass.newInstance();
t.setCode(CodeEnum.ERROR.getCode());
t.setMessage(CodeEnum.ERROR.getMsg());
} catch (Exception ex) {
}
}
return t;
}
在并发高的时候"处理时间"能有十几秒, 这个问题怎么解决? 是我配置有问题, 还是哪里有问题?