Skip to content

Commit

Permalink
🎨 优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
binarywang committed Sep 26, 2020
1 parent 5ecfaf7 commit 1d73443
Show file tree
Hide file tree
Showing 67 changed files with 276 additions and 233 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,23 +61,20 @@ protected void checkBackgroundProcessStarted() {
if (this.backgroundProcessStarted.getAndSet(true)) {
return;
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(WxMessageInMemoryDuplicateChecker.this.clearPeriod);
Long now = System.currentTimeMillis();
for (Map.Entry<String, Long> entry :
WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet()) {
if (now - entry.getValue() > WxMessageInMemoryDuplicateChecker.this.timeToLive) {
WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet().remove(entry);
}
Thread t = new Thread(() -> {
try {
while (true) {
Thread.sleep(WxMessageInMemoryDuplicateChecker.this.clearPeriod);
Long now = System.currentTimeMillis();
for (Map.Entry<String, Long> entry :
WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet()) {
if (now - entry.getValue() > WxMessageInMemoryDuplicateChecker.this.timeToLive) {
WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet().remove(entry);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
t.setDaemon(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
public class WxErrorException extends Exception {
private static final long serialVersionUID = -6357149550353160810L;

private WxError error;
private final WxError error;

public WxErrorException(String message) {
this(WxError.builder().errorCode(-1).errorMsg(message).build());
}

public WxErrorException(WxError error) {
super(error.toString());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package me.chanjar.weixin.common.error;

/**
* WxJava专用的runtime exception.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
* @date 2020-09-26
*/
public class WxRuntimeException extends RuntimeException {
private static final long serialVersionUID = 4881698471192264412L;

public WxRuntimeException(Throwable e) {
super(e);
}

public WxRuntimeException(String msg) {
super(msg);
}

public WxRuntimeException(String msg, Throwable e) {
super(msg, e);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -183,18 +183,15 @@ protected InternalSession getNewSession() {
public void add(InternalSession session) {
// 当第一次有session创建的时候,开启session清理线程
if (!this.backgroundProcessStarted.getAndSet(true)) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
// 每秒清理一次
Thread.sleep(StandardSessionManager.this.backgroundProcessorDelay * 1000L);
backgroundProcess();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
StandardSessionManager.this.log.error("SessionManagerImpl.backgroundProcess error", e);
}
Thread t = new Thread(() -> {
while (true) {
try {
// 每秒清理一次
Thread.sleep(StandardSessionManager.this.backgroundProcessorDelay * 1000L);
backgroundProcess();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
StandardSessionManager.this.log.error("SessionManagerImpl.backgroundProcess error", e);
}
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public static void checkRequiredFields(Object bean) throws WxErrorException {
if (!requiredFields.isEmpty()) {
String msg = String.format("必填字段【%s】必须提供值!", requiredFields);
log.debug(msg);
throw new WxErrorException(WxError.builder().errorMsg(msg).build());
throw new WxErrorException(msg);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultText;
Expand Down Expand Up @@ -40,7 +42,7 @@ public static Map<String, Object> xml2Map(String xmlString) {
map.put(element.getName(), element2MapOrString(element));
}
} catch (DocumentException | SAXException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}

return map;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import com.google.common.base.CharMatcher;
import com.google.common.io.BaseEncoding;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
Expand Down Expand Up @@ -77,7 +78,7 @@ private static String extractEncryptPart(String xml) {
Element root = document.getDocumentElement();
return root.getElementsByTagName("Encrypt").item(0).getTextContent();
} catch (Exception e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
}

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

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

// 解密
Expand Down Expand Up @@ -252,7 +253,7 @@ public String decrypt(String cipherText) {
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}

String xmlContent;
Expand All @@ -269,12 +270,12 @@ public String decrypt(String cipherText) {
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
fromAppid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET);
} catch (Exception e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}

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

return xmlContent;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public String getFileName() throws WxErrorException {
private String getFileName(CloseableHttpResponse response) throws WxErrorException {
Header[] contentDispositionHeader = response.getHeaders("Content-disposition");
if (contentDispositionHeader == null || contentDispositionHeader.length == 0) {
throw new WxErrorException(WxError.builder().errorMsg("无法获取到文件名").errorCode(99999).build());
throw new WxErrorException("无法获取到文件名");
}

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

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

Matcher m = PATTERN.matcher(content);
if (m.matches()) {
return m.group(1);
}

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

}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public static RequestExecutor<String, String> create(RequestHttp requestHttp) {
@NotNull
public String handleResponse(WxType wxType, String responseContent) throws WxErrorException {
if (responseContent.isEmpty()) {
throw new WxErrorException(WxError.builder().errorCode(9999).errorMsg("无响应内容").build());
throw new WxErrorException("无响应内容");
}

if (responseContent.startsWith("<xml>")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import jodd.util.MathUtil;
import me.chanjar.weixin.common.error.WxRuntimeException;

import java.util.List;

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

for (int i = 0; i < keyOrValue.length / 2; i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.util.concurrent.locks.Lock;

import com.github.jedis.lock.JedisLock;
import me.chanjar.weixin.common.error.WxRuntimeException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.util.Pool;

Expand All @@ -26,18 +27,18 @@ public JedisDistributedLock(Pool<Jedis> jedisPool, String key){
public void lock() {
try (Jedis jedis = jedisPool.getResource()) {
if (!lock.acquire(jedis)) {
throw new RuntimeException("acquire timeouted");
throw new WxRuntimeException("acquire timeouted");
}
} catch (InterruptedException e) {
throw new RuntimeException("lock failed", e);
throw new WxRuntimeException("lock failed", e);
}
}

@Override
public void lockInterruptibly() throws InterruptedException {
try (Jedis jedis = jedisPool.getResource()) {
if (!lock.acquire(jedis)) {
throw new RuntimeException("acquire timeouted");
throw new WxRuntimeException("acquire timeouted");
}
}
}
Expand All @@ -47,7 +48,7 @@ public boolean tryLock() {
try (Jedis jedis = jedisPool.getResource()) {
return lock.acquire(jedis);
} catch (InterruptedException e) {
throw new RuntimeException("lock failed", e);
throw new WxRuntimeException("lock failed", e);
}
}

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

@Override
public Condition newCondition() {
throw new RuntimeException("unsupported method");
throw new WxRuntimeException("unsupported method");
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package me.chanjar.weixin.common.util.locks;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.testng.annotations.BeforeTest;
Expand All @@ -12,6 +12,7 @@

import static org.testng.Assert.*;

@Slf4j
@Test(enabled = false)
public class RedisTemplateSimpleDistributedLockTest {

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

for (int i = 0; i < threadSize; i++) {
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
new Thread(() -> {
try {
startLatch.await();
} catch (InterruptedException e) {
log.error("unexpected exception", e);
}

redisLock.lock();
assertEquals(lockCurrentExecuteCounter.incrementAndGet(), 1, "临界区同时只能有一个线程执行");
lockCurrentExecuteCounter.decrementAndGet();
redisLock.unlock();
redisLock.lock();
assertEquals(lockCurrentExecuteCounter.incrementAndGet(), 1, "临界区同时只能有一个线程执行");
lockCurrentExecuteCounter.decrementAndGet();
redisLock.unlock();

endLatch.countDown();
}
endLatch.countDown();
}).start();
startLatch.countDown();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
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.WxSession;
import me.chanjar.weixin.common.session.WxSessionManager;
Expand Down Expand Up @@ -227,7 +228,7 @@ public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) thro
if (retryTimes + 1 > this.maxRetryTimes) {
log.warn("重试达到最大次数【{}】", this.maxRetryTimes);
//最后一次重试失败后,直接抛出异常,不再等待
throw new RuntimeException("微信服务端异常,超出重试次数");
throw new WxRuntimeException("微信服务端异常,超出重试次数");
}

WxError error = e.getError();
Expand All @@ -249,7 +250,7 @@ public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) thro
} 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 {
Expand Down Expand Up @@ -285,7 +286,7 @@ protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E
return null;
} catch (IOException e) {
log.error("\n【请求地址】: {}\n【请求参数】:{}\n【异常信息】:{}", uriWithAccessToken, dataForLog, e.getMessage());
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxCpErrorMsgEnum;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
Expand All @@ -30,7 +31,7 @@ public class WxCpExternalContactServiceImpl implements WxCpExternalContactServic
public WxCpContactWayResult addContactWay(@NonNull WxCpContactWayInfo info) throws WxErrorException {

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

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

final String url = this.mainService.getWxCpConfigStorage().getApiUrl(UPDATE_CONTACT_WAY);
Expand Down
Loading

0 comments on commit 1d73443

Please sign in to comment.