🎨 优化代码

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

@ -61,23 +61,20 @@ public class WxMessageInMemoryDuplicateChecker implements WxMessageDuplicateChec
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);

View File

@ -6,7 +6,11 @@ package me.chanjar.weixin.common.error;
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());

View File

@ -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);
}
}

View File

@ -183,18 +183,15 @@ public class StandardSessionManager implements WxSessionManager, InternalSession
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);
}
}
});

View File

@ -58,7 +58,7 @@ public class BeanUtils {
if (!requiredFields.isEmpty()) {
String msg = String.format("必填字段【%s】必须提供值", requiredFields);
log.debug(msg);
throw new WxErrorException(WxError.builder().errorMsg(msg).build());
throw new WxErrorException(msg);
}
}

View File

@ -3,6 +3,8 @@ package me.chanjar.weixin.common.util;
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;
@ -40,7 +42,7 @@ public class XmlUtils {
map.put(element.getName(), element2MapOrString(element));
}
} catch (DocumentException | SAXException e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
return map;

View File

@ -14,6 +14,7 @@ import javax.xml.parsers.ParserConfigurationException;
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;
@ -77,7 +78,7 @@ public class WxCryptUtil {
Element root = document.getDocumentElement();
return root.getElementsByTagName("Encrypt").item(0).getTextContent();
} catch (Exception e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
}
@ -198,7 +199,7 @@ public class WxCryptUtil {
// 使用BASE64对加密后的字符串进行编码
return BASE64.encodeToString(encrypted);
} catch (Exception e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
}
@ -224,7 +225,7 @@ public class WxCryptUtil {
// 验证安全签名
String signature = SHA1.gen(this.token, timeStamp, nonce, cipherText);
if (!signature.equals(msgSignature)) {
throw new RuntimeException("加密消息签名校验失败");
throw new WxRuntimeException("加密消息签名校验失败");
}
// 解密
@ -252,7 +253,7 @@ public class WxCryptUtil {
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
throw new RuntimeException(e);
throw new WxRuntimeException(e);
}
String xmlContent;
@ -269,12 +270,12 @@ public class WxCryptUtil {
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;

View File

@ -58,7 +58,7 @@ public class HttpResponseProxy {
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());
@ -76,7 +76,7 @@ public class HttpResponseProxy {
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);
@ -84,7 +84,7 @@ public class HttpResponseProxy {
return m.group(1);
}
throw new WxErrorException(WxError.builder().errorMsg("无法获取到文件名").errorCode(99999).build());
throw new WxErrorException("无法获取到文件名");
}
}

View File

@ -44,7 +44,7 @@ public abstract class SimplePostRequestExecutor<H, P> implements RequestExecutor
@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>")) {

View File

@ -5,6 +5,7 @@ import com.google.gson.JsonArray;
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;
@ -173,7 +174,7 @@ public class GsonHelper {
*/
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++) {

View File

@ -5,6 +5,7 @@ import java.util.concurrent.locks.Condition;
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;
@ -26,10 +27,10 @@ public class JedisDistributedLock implements Lock {
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);
}
}
@ -37,7 +38,7 @@ public class JedisDistributedLock implements Lock {
public void lockInterruptibly() throws InterruptedException {
try (Jedis jedis = jedisPool.getResource()) {
if (!lock.acquire(jedis)) {
throw new RuntimeException("acquire timeouted");
throw new WxRuntimeException("acquire timeouted");
}
}
}
@ -47,7 +48,7 @@ public class JedisDistributedLock implements Lock {
try (Jedis jedis = jedisPool.getResource()) {
return lock.acquire(jedis);
} catch (InterruptedException e) {
throw new RuntimeException("lock failed", e);
throw new WxRuntimeException("lock failed", e);
}
}
@ -67,7 +68,7 @@ public class JedisDistributedLock implements Lock {
@Override
public Condition newCondition() {
throw new RuntimeException("unsupported method");
throw new WxRuntimeException("unsupported method");
}
}

View File

@ -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;
@ -12,6 +12,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.testng.Assert.*;
@Slf4j
@Test(enabled = false)
public class RedisTemplateSimpleDistributedLockTest {
@ -40,19 +41,19 @@ public class RedisTemplateSimpleDistributedLockTest {
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();
redisLock.lock();
assertEquals(lockCurrentExecuteCounter.incrementAndGet(), 1, "临界区同时只能有一个线程执行");
lockCurrentExecuteCounter.decrementAndGet();
redisLock.unlock();
endLatch.countDown();
} catch (InterruptedException e) {
log.error("unexpected exception", e);
}
redisLock.lock();
assertEquals(lockCurrentExecuteCounter.incrementAndGet(), 1, "临界区同时只能有一个线程执行");
lockCurrentExecuteCounter.decrementAndGet();
redisLock.unlock();
endLatch.countDown();
}).start();
startLatch.countDown();
}