diff --git a/src/main/java/com/jfinal/weixin/sdk/api/AccessTokenApi.java b/src/main/java/com/jfinal/weixin/sdk/api/AccessTokenApi.java index 542682b7ba8309dd200f0a331d965e028e1c79b1..7c417b7bf9226ba438217208b2e798ff84b499da 100644 --- a/src/main/java/com/jfinal/weixin/sdk/api/AccessTokenApi.java +++ b/src/main/java/com/jfinal/weixin/sdk/api/AccessTokenApi.java @@ -32,46 +32,49 @@ public class AccessTokenApi { private static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"; // 用于手动设置的 accessToken - private static AccessToken accessToken=null; + private static ThreadLocal< AccessToken> accessTokenThreadLocal=new ThreadLocal<>(); public static void setAccessToken(AccessToken ak){ - accessToken=ak; + accessTokenThreadLocal.set(ak); ; } public static void removeAccessToken(){ - accessToken=null; + accessTokenThreadLocal.remove(); } + /** * 从缓存中获取 access token,如果未取到或者 access token 不可用则先更新再获取 * @return AccessToken accessToken */ public static AccessToken getAccessToken() { - if (accessToken!=null) - return accessToken; + if (accessTokenThreadLocal.get()!=null) { + return accessTokenThreadLocal.get(); + } + ApiConfig ac = ApiConfigKit.getApiConfig(); - AccessToken result = getAvailableAccessToken(ac); - if (result == null) { - synchronized(AccessTokenApi.class) { - result = getAvailableAccessToken(ac); - if (result == null) { - result = refreshAccessToken(ac); - } + AccessToken ak = getAvailableAccessToken(ac); + if (ak == null) { + ak = getAvailableAccessToken(ac); + if (ak == null) { + ak = refreshAccessToken(ac); } } - return result; + accessTokenThreadLocal.set(ak); + return ak; } private static AccessToken getAvailableAccessToken(ApiConfig ac) { // 利用 appId 与 accessToken 建立关联,支持多账户 IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache(); - String accessTokenJson = accessTokenCache.get(ac.getAppId()); if (StrKit.notBlank(accessTokenJson)) { AccessToken result = new AccessToken(accessTokenJson); + if (result != null && result.isAvailable()) { return result; } } + return null; }