🎨 优化代码

This commit is contained in:
Binary Wang
2020-09-26 16:15:56 +08:00
parent 5ecfaf7cd0
commit 1d7344309a
67 changed files with 277 additions and 234 deletions

View File

@@ -2,6 +2,7 @@ package me.chanjar.weixin.mp.api;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.common.api.WxMessageDuplicateChecker;
import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker;
@@ -50,10 +51,10 @@ import java.util.concurrent.*;
*
* @author Daniel Qian
*/
@Slf4j
@AllArgsConstructor
public class WxMpMessageRouter {
private static final int DEFAULT_THREAD_POOL_SIZE = 100;
protected final Logger log = LoggerFactory.getLogger(WxMpMessageRouter.class);
private final List<WxMpMessageRouterRule> rules = new ArrayList<>();
private final WxMpService wxMpService;
@@ -201,7 +202,7 @@ public class WxMpMessageRouter {
} else {
res = rule.service(wxMessage, context, mpService, this.sessionManager, this.exceptionHandler);
// 在同步操作结束session访问结束
this.log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUser());
log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUser());
sessionEndAccess(wxMessage);
}
}
@@ -214,14 +215,14 @@ public class WxMpMessageRouter {
for (Future<?> future : futures) {
try {
future.get();
WxMpMessageRouter.this.log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUser());
log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUser());
// 异步操作结束session访问结束
sessionEndAccess(wxMessage);
} catch (InterruptedException e) {
WxMpMessageRouter.this.log.error("Error happened when wait task finish", e);
log.error("Error happened when wait task finish", e);
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
WxMpMessageRouter.this.log.error("Error happened when wait task finish", e);
log.error("Error happened when wait task finish", e);
}
}
});

View File

@@ -7,10 +7,7 @@ import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.regex.Pattern;
public class WxMpMessageRouterRule {
@@ -130,9 +127,7 @@ public class WxMpMessageRouterRule {
public WxMpMessageRouterRule interceptor(WxMpMessageInterceptor interceptor, WxMpMessageInterceptor... otherInterceptors) {
this.interceptors.add(interceptor);
if (otherInterceptors != null && otherInterceptors.length > 0) {
for (WxMpMessageInterceptor i : otherInterceptors) {
this.interceptors.add(i);
}
Collections.addAll(this.interceptors, otherInterceptors);
}
return this;
}

View File

@@ -12,9 +12,7 @@ import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.common.util.http.RequestHttp;
import me.chanjar.weixin.mp.bean.WxMpSemanticQuery;
import me.chanjar.weixin.mp.bean.result.WxMpCurrentAutoReplyInfo;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpSemanticQueryResult;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.enums.WxMpApiUrl;

View File

@@ -17,6 +17,7 @@ import me.chanjar.weixin.common.enums.TicketType;
import me.chanjar.weixin.common.enums.WxType;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.session.StandardSessionManager;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.DataUtils;
@@ -28,9 +29,7 @@ import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.mp.bean.WxMpSemanticQuery;
import me.chanjar.weixin.mp.bean.result.WxMpCurrentAutoReplyInfo;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpSemanticQueryResult;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.enums.WxMpApiUrl;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
@@ -203,9 +202,8 @@ public abstract class BaseWxMpServiceImpl<H, P> implements WxMpService, RequestH
@Override
public String shortUrl(String longUrl) throws WxErrorException {
if (longUrl.contains("&access_token=")) {
throw new WxErrorException(WxError.builder().errorCode(-1)
.errorMsg("要转换的网址中存在非法字符{&access_token=会导致微信接口报错属于微信bug请调整地址否则不建议使用此方法")
.build());
throw new WxErrorException("要转换的网址中存在非法字符{&access_token=" +
"会导致微信接口报错属于微信bug请调整地址否则不建议使用此方法");
}
JsonObject o = new JsonObject();
@@ -303,7 +301,7 @@ public abstract class BaseWxMpServiceImpl<H, P> implements WxMpService, RequestH
if (retryTimes + 1 > this.maxRetryTimes) {
log.warn("重试达到最大次数【{}】", maxRetryTimes);
//最后一次重试失败后,直接抛出异常,不再等待
throw new RuntimeException("微信服务端异常,超出重试次数");
throw new WxRuntimeException("微信服务端异常,超出重试次数");
}
WxError error = e.getError();
@@ -314,7 +312,7 @@ public abstract class BaseWxMpServiceImpl<H, P> implements WxMpService, RequestH
log.warn("微信系统繁忙,{} ms 后重试(第{}次)", sleepMillis, retryTimes + 1);
Thread.sleep(sleepMillis);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
throw new WxRuntimeException(e1);
}
} else {
throw e;
@@ -323,7 +321,7 @@ public abstract class BaseWxMpServiceImpl<H, P> implements WxMpService, RequestH
} while (retryTimes++ < this.maxRetryTimes);
log.warn("重试达到最大次数【{}】", this.maxRetryTimes);
throw new RuntimeException("微信服务端异常,超出重试次数");
throw new WxRuntimeException("微信服务端异常,超出重试次数");
}
protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException {
@@ -448,7 +446,7 @@ public abstract class BaseWxMpServiceImpl<H, P> implements WxMpService, RequestH
return this;
}
throw new RuntimeException(String.format("无法找到对应【%s】的公众号配置信息请核实", mpId));
throw new WxRuntimeException(String.format("无法找到对应【%s】的公众号配置信息请核实", mpId));
}
@Override

View File

@@ -115,11 +115,11 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
@Override
public WxMpKfMsgList kfMsgList(Date startTime, Date endTime, Long msgId, Integer number) throws WxErrorException {
if (number > 10000) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("非法参数请求每次最多查询10000条记录").build());
throw new WxErrorException("非法参数请求每次最多查询10000条记录");
}
if (startTime.after(endTime)) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("起始时间不能晚于结束时间!").build());
throw new WxErrorException("起始时间不能晚于结束时间!");
}
JsonObject param = new JsonObject();

View File

@@ -29,7 +29,7 @@ public class WxMpQrcodeServiceImpl implements WxMpQrcodeService {
@Override
public WxMpQrCodeTicket qrCodeCreateTmpTicket(int sceneId, Integer expireSeconds) throws WxErrorException {
if (sceneId == 0) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("临时二维码场景值不能为0").build());
throw new WxErrorException("临时二维码场景值不能为0");
}
return this.createQrCode("QR_SCENE", null, sceneId, expireSeconds);
@@ -38,7 +38,7 @@ public class WxMpQrcodeServiceImpl implements WxMpQrcodeService {
@Override
public WxMpQrCodeTicket qrCodeCreateTmpTicket(String sceneStr, Integer expireSeconds) throws WxErrorException {
if (StringUtils.isBlank(sceneStr)) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("临时二维码场景值不能为空!").build());
throw new WxErrorException("临时二维码场景值不能为空!");
}
return this.createQrCode("QR_STR_SCENE", sceneStr, null, expireSeconds);
@@ -48,8 +48,7 @@ public class WxMpQrcodeServiceImpl implements WxMpQrcodeService {
throws WxErrorException {
//expireSeconds 该二维码有效时间,以秒为单位。 最大不超过2592000即30天此字段如果不填则默认有效期为30秒。
if (expireSeconds != null && expireSeconds > 2592000) {
throw new WxErrorException(WxError.builder().errorCode(-1)
.errorMsg("临时二维码有效时间最大不能超过2592000即30天").build());
throw new WxErrorException("临时二维码有效时间最大不能超过2592000即30天");
}
if (expireSeconds == null) {
@@ -84,9 +83,7 @@ public class WxMpQrcodeServiceImpl implements WxMpQrcodeService {
@Override
public WxMpQrCodeTicket qrCodeCreateLastTicket(int sceneId) throws WxErrorException {
if (sceneId < 1 || sceneId > 100000) {
throw new WxErrorException(WxError.builder().errorCode(-1)
.errorMsg("永久二维码的场景值目前只支持1--100000")
.build());
throw new WxErrorException("永久二维码的场景值目前只支持1--100000");
}
return this.getQrCodeTicket("QR_LIMIT_SCENE", null, sceneId, null);
@@ -113,7 +110,7 @@ public class WxMpQrcodeServiceImpl implements WxMpQrcodeService {
return resultUrl;
} catch (UnsupportedEncodingException e) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg(e.getMessage()).build());
throw new WxErrorException(e.getMessage());
}
}

View File

@@ -1,6 +1,7 @@
package me.chanjar.weixin.mp.api.impl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.http.HttpType;
import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder;
import me.chanjar.weixin.common.util.http.apache.DefaultApacheHttpClientBuilder;
@@ -92,10 +93,10 @@ public class WxMpServiceHttpClientImpl extends BaseWxMpServiceImpl<CloseableHttp
httpGet.releaseConnection();
}
} catch (IOException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
} finally {
if (locked) {
lock.unlock();

View File

@@ -5,6 +5,7 @@ import jodd.http.HttpRequest;
import jodd.http.ProxyInfo;
import jodd.http.net.SocketHttpConnectionProvider;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.http.HttpType;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
@@ -77,7 +78,7 @@ public class WxMpServiceJoddHttpImpl extends BaseWxMpServiceImpl<HttpConnectionP
return this.extractAccessToken(request.send().bodyText());
} catch (InterruptedException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
} finally {
if (locked) {
lock.unlock();

View File

@@ -1,6 +1,7 @@
package me.chanjar.weixin.mp.api.impl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.http.HttpType;
import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
@@ -59,9 +60,9 @@ public class WxMpServiceOkHttpImpl extends BaseWxMpServiceImpl<OkHttpClient, OkH
Response response = getRequestHttpClient().newCall(request).execute();
return this.extractAccessToken(Objects.requireNonNull(response.body()).string());
} catch (IOException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
} finally {
if (locked) {
lock.unlock();

View File

@@ -5,6 +5,7 @@ import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.enums.WxType;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor;
import me.chanjar.weixin.common.util.http.URIUtil;
@@ -75,7 +76,7 @@ public class WxOAuth2ServiceImpl implements WxOAuth2Service {
String responseText = executor.execute(url, null, WxType.MP);
return WxMpUser.fromJson(responseText);
} catch (IOException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
}
@@ -86,7 +87,7 @@ public class WxOAuth2ServiceImpl implements WxOAuth2Service {
try {
SimpleGetRequestExecutor.create(this.wxMpService.getRequestHttp()).execute(url, null, WxType.MP);
} catch (IOException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
} catch (WxErrorException e) {
return false;
}

View File

@@ -5,6 +5,7 @@ import com.thoughtworks.xstream.annotations.XStreamConverter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.XmlUtils;
import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
@@ -716,7 +717,7 @@ public class WxMpXmlMessage implements Serializable {
try {
return fromEncryptedXml(IOUtils.toString(is, StandardCharsets.UTF_8), wxMpConfigStorage, timestamp, nonce, msgSignature);
} catch (IOException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
}

View File

@@ -2,6 +2,7 @@ package me.chanjar.weixin.mp.util.json;
import com.google.gson.*;
import me.chanjar.weixin.common.api.WxConsts.KefuMsgType;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.apache.commons.lang3.StringUtils;
@@ -96,7 +97,7 @@ public class WxMpKefuMessageGsonAdapter implements JsonSerializer<WxMpKefuMessag
break;
}
default: {
throw new RuntimeException("非法消息类型,暂不支持");
throw new WxRuntimeException("非法消息类型,暂不支持");
}
}

View File

@@ -41,7 +41,7 @@ public class MaterialUploadApacheHttpRequestExecutor extends MaterialUploadReque
}
if (material == null) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("非法请求material参数为空").build());
throw new WxErrorException("非法请求material参数为空");
}
File file = material.getFile();

View File

@@ -37,7 +37,7 @@ public class MaterialUploadJoddHttpRequestExecutor extends MaterialUploadRequest
request.withConnectionProvider(requestHttp.getRequestHttpClient());
if (material == null) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("非法请求material参数为空").build());
throw new WxErrorException("非法请求material参数为空");
}
File file = material.getFile();

View File

@@ -31,7 +31,7 @@ public class MaterialUploadOkhttpRequestExecutor extends MaterialUploadRequestEx
public WxMpMaterialUploadResult execute(String uri, WxMpMaterial material, WxType wxType) throws WxErrorException, IOException {
logger.debug("MaterialUploadOkhttpRequestExecutor is running");
if (material == null) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("非法请求material参数为空").build());
throw new WxErrorException("非法请求material参数为空");
}
File file = material.getFile();
if (file == null || !file.exists()) {

View File

@@ -32,7 +32,7 @@ public class MediaImgUploadApacheHttpRequestExecutor extends MediaImgUploadReque
@Override
public WxMediaImgUploadResult execute(String uri, File data, WxType wxType) throws WxErrorException, IOException {
if (data == null) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("文件对象为空").build());
throw new WxErrorException("文件对象为空");
}
HttpPost httpPost = new HttpPost(uri);

View File

@@ -29,7 +29,7 @@ public class MediaImgUploadHttpRequestExecutor extends MediaImgUploadRequestExec
@Override
public WxMediaImgUploadResult execute(String uri, File data, WxType wxType) throws WxErrorException, IOException {
if (data == null) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("文件对象为空").build());
throw new WxErrorException("文件对象为空");
}
HttpRequest request = HttpRequest.post(uri);

View File

@@ -37,7 +37,7 @@ public abstract class QrCodeRequestExecutor<H, P> implements RequestExecutor<Fil
case OK_HTTP:
return new QrCodeOkhttpRequestExecutor(requestHttp);
default:
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("不支持的http框架").build());
throw new WxErrorException("不支持的http框架");
}
}

View File

@@ -33,7 +33,7 @@ public class VoiceUploadApacheHttpRequestExecutor extends VoiceUploadRequestExec
@Override
public Boolean execute(String uri, File data, WxType wxType) throws WxErrorException, IOException {
if (data == null) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("文件对象为空").build());
throw new WxErrorException("文件对象为空");
}
HttpPost httpPost = new HttpPost(uri);

View File

@@ -3,6 +3,7 @@ package me.chanjar.weixin.mp.api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import org.testng.annotations.*;
@@ -25,7 +26,7 @@ public class WxMpBusyRetryTest {
RequestExecutor<T, E> executor, String uri, E data)
throws WxErrorException {
log.info("Executed");
throw new WxErrorException(WxError.builder().errorCode(-1).build());
throw new WxErrorException("something");
}
};
@@ -43,18 +44,15 @@ public class WxMpBusyRetryTest {
public void testRetryInThreadPool(final WxMpService service) throws InterruptedException, ExecutionException {
// 当线程池中的线程复用的时候,还是能保证相同的重试次数
ExecutorService executorService = Executors.newFixedThreadPool(1);
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("=====================");
System.out.println(Thread.currentThread().getName() + ": testRetry");
service.execute(null, (String)null, null);
} catch (WxErrorException e) {
throw new RuntimeException(e);
} catch (RuntimeException e) {
// OK
}
Runnable runnable = () -> {
try {
System.out.println("=====================");
System.out.println(Thread.currentThread().getName() + ": testRetry");
service.execute(null, (String)null, null);
} catch (WxErrorException e) {
throw new WxRuntimeException(e);
} catch (RuntimeException e) {
// OK
}
};
Future<?> submit1 = executorService.submit(runnable);

View File

@@ -97,14 +97,11 @@ public class WxMpMessageRouterTest {
}).end();
final WxMpXmlMessage m = new WxMpXmlMessage();
Runnable r = new Runnable() {
@Override
public void run() {
router.route(m);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Runnable r = () -> {
router.route(m);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
};
for (int i = 0; i < 10; i++) {

View File

@@ -82,15 +82,12 @@ public class BaseWxMpServiceImplTest {
// 测试多线程刷新accessToken时是否重复刷新
wxService.getWxMpConfigStorage().expireAccessToken();
final Set<String> set = Sets.newConcurrentHashSet();
Runnable r = new Runnable() {
@Override
public void run() {
try {
String accessToken = wxService.getAccessToken();
set.add(accessToken);
} catch (WxErrorException e) {
e.printStackTrace();
}
Runnable r = () -> {
try {
String accessToken = wxService.getAccessToken();
set.add(accessToken);
} catch (WxErrorException e) {
e.printStackTrace();
}
};

View File

@@ -4,6 +4,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.locks.ReentrantLock;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -23,7 +24,7 @@ public class ApiTestModule implements Module {
public void configure(Binder binder) {
try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(TEST_CONFIG_XML)) {
if (inputStream == null) {
throw new RuntimeException("测试配置文件【" + TEST_CONFIG_XML + "】未找到请参照test-config-sample.xml文件生成");
throw new WxRuntimeException("测试配置文件【" + TEST_CONFIG_XML + "】未找到请参照test-config-sample.xml文件生成");
}
TestConfigStorage config = this.fromXml(TestConfigStorage.class, inputStream);