Skip to content

Commit 1d73443

Browse files
committed
🎨 优化代码
1 parent 5ecfaf7 commit 1d73443

File tree

67 files changed

+276
-233
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+276
-233
lines changed

weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -61,23 +61,20 @@ protected void checkBackgroundProcessStarted() {
6161
if (this.backgroundProcessStarted.getAndSet(true)) {
6262
return;
6363
}
64-
Thread t = new Thread(new Runnable() {
65-
@Override
66-
public void run() {
67-
try {
68-
while (true) {
69-
Thread.sleep(WxMessageInMemoryDuplicateChecker.this.clearPeriod);
70-
Long now = System.currentTimeMillis();
71-
for (Map.Entry<String, Long> entry :
72-
WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet()) {
73-
if (now - entry.getValue() > WxMessageInMemoryDuplicateChecker.this.timeToLive) {
74-
WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet().remove(entry);
75-
}
64+
Thread t = new Thread(() -> {
65+
try {
66+
while (true) {
67+
Thread.sleep(WxMessageInMemoryDuplicateChecker.this.clearPeriod);
68+
Long now = System.currentTimeMillis();
69+
for (Map.Entry<String, Long> entry :
70+
WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet()) {
71+
if (now - entry.getValue() > WxMessageInMemoryDuplicateChecker.this.timeToLive) {
72+
WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet().remove(entry);
7673
}
7774
}
78-
} catch (InterruptedException e) {
79-
Thread.currentThread().interrupt();
8075
}
76+
} catch (InterruptedException e) {
77+
Thread.currentThread().interrupt();
8178
}
8279
});
8380
t.setDaemon(true);

weixin-java-common/src/main/java/me/chanjar/weixin/common/error/WxErrorException.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@
66
public class WxErrorException extends Exception {
77
private static final long serialVersionUID = -6357149550353160810L;
88

9-
private WxError error;
9+
private final WxError error;
10+
11+
public WxErrorException(String message) {
12+
this(WxError.builder().errorCode(-1).errorMsg(message).build());
13+
}
1014

1115
public WxErrorException(WxError error) {
1216
super(error.toString());
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package me.chanjar.weixin.common.error;
2+
3+
/**
4+
* WxJava专用的runtime exception.
5+
*
6+
* @author <a href="https://github.com/binarywang">Binary Wang</a>
7+
* @date 2020-09-26
8+
*/
9+
public class WxRuntimeException extends RuntimeException {
10+
private static final long serialVersionUID = 4881698471192264412L;
11+
12+
public WxRuntimeException(Throwable e) {
13+
super(e);
14+
}
15+
16+
public WxRuntimeException(String msg) {
17+
super(msg);
18+
}
19+
20+
public WxRuntimeException(String msg, Throwable e) {
21+
super(msg, e);
22+
}
23+
}

weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -183,18 +183,15 @@ protected InternalSession getNewSession() {
183183
public void add(InternalSession session) {
184184
// 当第一次有session创建的时候,开启session清理线程
185185
if (!this.backgroundProcessStarted.getAndSet(true)) {
186-
Thread t = new Thread(new Runnable() {
187-
@Override
188-
public void run() {
189-
while (true) {
190-
try {
191-
// 每秒清理一次
192-
Thread.sleep(StandardSessionManager.this.backgroundProcessorDelay * 1000L);
193-
backgroundProcess();
194-
} catch (InterruptedException e) {
195-
Thread.currentThread().interrupt();
196-
StandardSessionManager.this.log.error("SessionManagerImpl.backgroundProcess error", e);
197-
}
186+
Thread t = new Thread(() -> {
187+
while (true) {
188+
try {
189+
// 每秒清理一次
190+
Thread.sleep(StandardSessionManager.this.backgroundProcessorDelay * 1000L);
191+
backgroundProcess();
192+
} catch (InterruptedException e) {
193+
Thread.currentThread().interrupt();
194+
StandardSessionManager.this.log.error("SessionManagerImpl.backgroundProcess error", e);
198195
}
199196
}
200197
});

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/BeanUtils.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public static void checkRequiredFields(Object bean) throws WxErrorException {
5858
if (!requiredFields.isEmpty()) {
5959
String msg = String.format("必填字段【%s】必须提供值!", requiredFields);
6060
log.debug(msg);
61-
throw new WxErrorException(WxError.builder().errorMsg(msg).build());
61+
throw new WxErrorException(msg);
6262
}
6363
}
6464

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/XmlUtils.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import com.google.common.collect.Lists;
44
import com.google.common.collect.Maps;
55
import com.google.common.collect.Sets;
6+
import me.chanjar.weixin.common.error.WxErrorException;
7+
import me.chanjar.weixin.common.error.WxRuntimeException;
68
import org.dom4j.*;
79
import org.dom4j.io.SAXReader;
810
import org.dom4j.tree.DefaultText;
@@ -40,7 +42,7 @@ public static Map<String, Object> xml2Map(String xmlString) {
4042
map.put(element.getName(), element2MapOrString(element));
4143
}
4244
} catch (DocumentException | SAXException e) {
43-
throw new RuntimeException(e);
45+
throw new WxRuntimeException(e);
4446
}
4547

4648
return map;

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import com.google.common.base.CharMatcher;
1616
import com.google.common.io.BaseEncoding;
17+
import me.chanjar.weixin.common.error.WxRuntimeException;
1718
import org.apache.commons.codec.binary.Base64;
1819
import org.w3c.dom.Document;
1920
import org.w3c.dom.Element;
@@ -77,7 +78,7 @@ private static String extractEncryptPart(String xml) {
7778
Element root = document.getDocumentElement();
7879
return root.getElementsByTagName("Encrypt").item(0).getTextContent();
7980
} catch (Exception e) {
80-
throw new RuntimeException(e);
81+
throw new WxRuntimeException(e);
8182
}
8283
}
8384

@@ -198,7 +199,7 @@ protected String encrypt(String randomStr, String plainText) {
198199
// 使用BASE64对加密后的字符串进行编码
199200
return BASE64.encodeToString(encrypted);
200201
} catch (Exception e) {
201-
throw new RuntimeException(e);
202+
throw new WxRuntimeException(e);
202203
}
203204
}
204205

@@ -224,7 +225,7 @@ public String decrypt(String msgSignature, String timeStamp, String nonce, Strin
224225
// 验证安全签名
225226
String signature = SHA1.gen(this.token, timeStamp, nonce, cipherText);
226227
if (!signature.equals(msgSignature)) {
227-
throw new RuntimeException("加密消息签名校验失败");
228+
throw new WxRuntimeException("加密消息签名校验失败");
228229
}
229230

230231
// 解密
@@ -252,7 +253,7 @@ public String decrypt(String cipherText) {
252253
// 解密
253254
original = cipher.doFinal(encrypted);
254255
} catch (Exception e) {
255-
throw new RuntimeException(e);
256+
throw new WxRuntimeException(e);
256257
}
257258

258259
String xmlContent;
@@ -269,12 +270,12 @@ public String decrypt(String cipherText) {
269270
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
270271
fromAppid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET);
271272
} catch (Exception e) {
272-
throw new RuntimeException(e);
273+
throw new WxRuntimeException(e);
273274
}
274275

275276
// appid不相同的情况 暂时忽略这段判断
276277
// if (!fromAppid.equals(this.appidOrCorpid)) {
277-
// throw new RuntimeException("AppID不正确,请核实!");
278+
// throw new WxRuntimeException("AppID不正确,请核实!");
278279
// }
279280

280281
return xmlContent;

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/HttpResponseProxy.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public String getFileName() throws WxErrorException {
5858
private String getFileName(CloseableHttpResponse response) throws WxErrorException {
5959
Header[] contentDispositionHeader = response.getHeaders("Content-disposition");
6060
if (contentDispositionHeader == null || contentDispositionHeader.length == 0) {
61-
throw new WxErrorException(WxError.builder().errorMsg("无法获取到文件名").errorCode(99999).build());
61+
throw new WxErrorException("无法获取到文件名");
6262
}
6363

6464
return this.extractFileNameFromContentString(contentDispositionHeader[0].getValue());
@@ -76,15 +76,15 @@ private String getFileName(Response response) throws WxErrorException {
7676

7777
private String extractFileNameFromContentString(String content) throws WxErrorException {
7878
if (content == null || content.length() == 0) {
79-
throw new WxErrorException(WxError.builder().errorMsg("无法获取到文件名").errorCode(99999).build());
79+
throw new WxErrorException("无法获取到文件名");
8080
}
8181

8282
Matcher m = PATTERN.matcher(content);
8383
if (m.matches()) {
8484
return m.group(1);
8585
}
8686

87-
throw new WxErrorException(WxError.builder().errorMsg("无法获取到文件名").errorCode(99999).build());
87+
throw new WxErrorException("无法获取到文件名");
8888
}
8989

9090
}

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public static RequestExecutor<String, String> create(RequestHttp requestHttp) {
4444
@NotNull
4545
public String handleResponse(WxType wxType, String responseContent) throws WxErrorException {
4646
if (responseContent.isEmpty()) {
47-
throw new WxErrorException(WxError.builder().errorCode(9999).errorMsg("无响应内容").build());
47+
throw new WxErrorException("无响应内容");
4848
}
4949

5050
if (responseContent.startsWith("<xml>")) {

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import com.google.gson.JsonElement;
66
import com.google.gson.JsonObject;
77
import jodd.util.MathUtil;
8+
import me.chanjar.weixin.common.error.WxRuntimeException;
89

910
import java.util.List;
1011

@@ -173,7 +174,7 @@ public static JsonObject buildJsonObject(Object... keyOrValue) {
173174
*/
174175
public static void put(JsonObject jsonObject, Object... keyOrValue) {
175176
if (MathUtil.isOdd(keyOrValue.length)) {
176-
throw new RuntimeException("参数个数必须为偶数");
177+
throw new WxRuntimeException("参数个数必须为偶数");
177178
}
178179

179180
for (int i = 0; i < keyOrValue.length / 2; i++) {

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/locks/JedisDistributedLock.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import java.util.concurrent.locks.Lock;
66

77
import com.github.jedis.lock.JedisLock;
8+
import me.chanjar.weixin.common.error.WxRuntimeException;
89
import redis.clients.jedis.Jedis;
910
import redis.clients.jedis.util.Pool;
1011

@@ -26,18 +27,18 @@ public JedisDistributedLock(Pool<Jedis> jedisPool, String key){
2627
public void lock() {
2728
try (Jedis jedis = jedisPool.getResource()) {
2829
if (!lock.acquire(jedis)) {
29-
throw new RuntimeException("acquire timeouted");
30+
throw new WxRuntimeException("acquire timeouted");
3031
}
3132
} catch (InterruptedException e) {
32-
throw new RuntimeException("lock failed", e);
33+
throw new WxRuntimeException("lock failed", e);
3334
}
3435
}
3536

3637
@Override
3738
public void lockInterruptibly() throws InterruptedException {
3839
try (Jedis jedis = jedisPool.getResource()) {
3940
if (!lock.acquire(jedis)) {
40-
throw new RuntimeException("acquire timeouted");
41+
throw new WxRuntimeException("acquire timeouted");
4142
}
4243
}
4344
}
@@ -47,7 +48,7 @@ public boolean tryLock() {
4748
try (Jedis jedis = jedisPool.getResource()) {
4849
return lock.acquire(jedis);
4950
} catch (InterruptedException e) {
50-
throw new RuntimeException("lock failed", e);
51+
throw new WxRuntimeException("lock failed", e);
5152
}
5253
}
5354

@@ -67,7 +68,7 @@ public void unlock() {
6768

6869
@Override
6970
public Condition newCondition() {
70-
throw new RuntimeException("unsupported method");
71+
throw new WxRuntimeException("unsupported method");
7172
}
7273

7374
}

weixin-java-common/src/test/java/me/chanjar/weixin/common/util/locks/RedisTemplateSimpleDistributedLockTest.java

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package me.chanjar.weixin.common.util.locks;
22

3-
import lombok.SneakyThrows;
3+
import lombok.extern.slf4j.Slf4j;
44
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
55
import org.springframework.data.redis.core.StringRedisTemplate;
66
import org.testng.annotations.BeforeTest;
@@ -12,6 +12,7 @@
1212

1313
import static org.testng.Assert.*;
1414

15+
@Slf4j
1516
@Test(enabled = false)
1617
public class RedisTemplateSimpleDistributedLockTest {
1718

@@ -40,19 +41,19 @@ public void testLockExclusive() throws InterruptedException {
4041
final CountDownLatch endLatch = new CountDownLatch(threadSize);
4142

4243
for (int i = 0; i < threadSize; i++) {
43-
new Thread(new Runnable() {
44-
@SneakyThrows
45-
@Override
46-
public void run() {
44+
new Thread(() -> {
45+
try {
4746
startLatch.await();
47+
} catch (InterruptedException e) {
48+
log.error("unexpected exception", e);
49+
}
4850

49-
redisLock.lock();
50-
assertEquals(lockCurrentExecuteCounter.incrementAndGet(), 1, "临界区同时只能有一个线程执行");
51-
lockCurrentExecuteCounter.decrementAndGet();
52-
redisLock.unlock();
51+
redisLock.lock();
52+
assertEquals(lockCurrentExecuteCounter.incrementAndGet(), 1, "临界区同时只能有一个线程执行");
53+
lockCurrentExecuteCounter.decrementAndGet();
54+
redisLock.unlock();
5355

54-
endLatch.countDown();
55-
}
56+
endLatch.countDown();
5657
}).start();
5758
startLatch.countDown();
5859
}

weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/BaseWxCpServiceImpl.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import me.chanjar.weixin.common.enums.WxType;
1010
import me.chanjar.weixin.common.error.WxError;
1111
import me.chanjar.weixin.common.error.WxErrorException;
12+
import me.chanjar.weixin.common.error.WxRuntimeException;
1213
import me.chanjar.weixin.common.session.StandardSessionManager;
1314
import me.chanjar.weixin.common.session.WxSession;
1415
import me.chanjar.weixin.common.session.WxSessionManager;
@@ -227,7 +228,7 @@ public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) thro
227228
if (retryTimes + 1 > this.maxRetryTimes) {
228229
log.warn("重试达到最大次数【{}】", this.maxRetryTimes);
229230
//最后一次重试失败后,直接抛出异常,不再等待
230-
throw new RuntimeException("微信服务端异常,超出重试次数");
231+
throw new WxRuntimeException("微信服务端异常,超出重试次数");
231232
}
232233

233234
WxError error = e.getError();
@@ -249,7 +250,7 @@ public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) thro
249250
} while (retryTimes++ < this.maxRetryTimes);
250251

251252
log.warn("重试达到最大次数【{}】", this.maxRetryTimes);
252-
throw new RuntimeException("微信服务端异常,超出重试次数");
253+
throw new WxRuntimeException("微信服务端异常,超出重试次数");
253254
}
254255

255256
protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException {
@@ -285,7 +286,7 @@ protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E
285286
return null;
286287
} catch (IOException e) {
287288
log.error("\n【请求地址】: {}\n【请求参数】:{}\n【异常信息】:{}", uriWithAccessToken, dataForLog, e.getMessage());
288-
throw new RuntimeException(e);
289+
throw new WxRuntimeException(e);
289290
}
290291
}
291292

weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/WxCpExternalContactServiceImpl.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import lombok.RequiredArgsConstructor;
77
import me.chanjar.weixin.common.error.WxCpErrorMsgEnum;
88
import me.chanjar.weixin.common.error.WxErrorException;
9+
import me.chanjar.weixin.common.error.WxRuntimeException;
910
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
1011
import me.chanjar.weixin.cp.api.WxCpService;
1112
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
@@ -30,7 +31,7 @@ public class WxCpExternalContactServiceImpl implements WxCpExternalContactServic
3031
public WxCpContactWayResult addContactWay(@NonNull WxCpContactWayInfo info) throws WxErrorException {
3132

3233
if (info.getContactWay().getUsers() != null && info.getContactWay().getUsers().size() > 100) {
33-
throw new RuntimeException("「联系我」使用人数默认限制不超过100人(包括部门展开后的人数)");
34+
throw new WxRuntimeException("「联系我」使用人数默认限制不超过100人(包括部门展开后的人数)");
3435
}
3536

3637
final String url = this.mainService.getWxCpConfigStorage().getApiUrl(ADD_CONTACT_WAY);
@@ -52,10 +53,10 @@ public WxCpContactWayInfo getContactWay(@NonNull String configId) throws WxError
5253
@Override
5354
public WxCpBaseResp updateContactWay(@NonNull WxCpContactWayInfo info) throws WxErrorException {
5455
if (StringUtils.isBlank(info.getContactWay().getConfigId())) {
55-
throw new RuntimeException("更新「联系我」方式需要指定configId");
56+
throw new WxRuntimeException("更新「联系我」方式需要指定configId");
5657
}
5758
if (info.getContactWay().getUsers() != null && info.getContactWay().getUsers().size() > 100) {
58-
throw new RuntimeException("「联系我」使用人数默认限制不超过100人(包括部门展开后的人数)");
59+
throw new WxRuntimeException("「联系我」使用人数默认限制不超过100人(包括部门展开后的人数)");
5960
}
6061

6162
final String url = this.mainService.getWxCpConfigStorage().getApiUrl(UPDATE_CONTACT_WAY);

0 commit comments

Comments
 (0)