添加锁避免高并发冲突

This commit is contained in:
2025-06-13 14:26:05 +08:00
parent cd4678120d
commit 04e2ade669

View File

@ -8,6 +8,7 @@ import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
public class WxMpUtil {
private static final String GET_WXA_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";
@ -16,25 +17,31 @@ public class WxMpUtil {
public static final String GET_USER_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";
private static final Map<String, String> tokens = new ConcurrentHashMap<>();
private static final Map<String, Date> expireTimes = new ConcurrentHashMap<>();
private static final ReentrantLock lock = new ReentrantLock();
private static String getAccessToken(String appId, String appSecret) {
if (expireTimes.containsKey(appId)) {
Date expireTime = expireTimes.get(appId);
if (expireTime.getTime() < System.currentTimeMillis()) {
lock.lock();
try {
if (expireTimes.containsKey(appId)) {
Date expireTime = expireTimes.get(appId);
if (expireTime.getTime() < System.currentTimeMillis()) {
tokens.remove(appId);
}
} else {
tokens.remove(appId);
}
} else {
tokens.remove(appId);
return tokens.computeIfAbsent(appId, (k) -> {
String url = String.format(ACCESS_TOKEN_URL, appId, appSecret);
String response = HttpUtil.get(url);
JSONObject jsonObject = JSONObject.parseObject(response);
String token = jsonObject.getString("access_token");
Date expireTime = new Date(System.currentTimeMillis() + jsonObject.getInteger("expires_in") * 1000 / 2);
expireTimes.put(appId, expireTime);
return token;
});
} finally {
lock.unlock();
}
return tokens.computeIfAbsent(appId, (k) -> {
String url = String.format(ACCESS_TOKEN_URL, appId, appSecret);
String response = HttpUtil.get(url);
JSONObject jsonObject = JSONObject.parseObject(response);
String token = jsonObject.getString("access_token");
Date expireTime = new Date(System.currentTimeMillis() + jsonObject.getInteger("expires_in") * 1000 / 2);
expireTimes.put(appId, expireTime);
return token;
});
}
public static void generateWXAQRCode(String appId, String appSecret, String envVersion, String path, String filePath) throws Exception {