1
0
mirror of https://github.com/silenceper/wechat.git synced 2026-02-12 00:32:26 +08:00
This commit is contained in:
yangyl12345
2024-11-26 02:56:09 +00:00
committed by GitHub

View File

@@ -105,6 +105,7 @@ type StableAccessToken struct {
appSecret string appSecret string
cacheKeyPrefix string cacheKeyPrefix string
cache cache.Cache cache cache.Cache
accessTokenLock *sync.Mutex
} }
// NewStableAccessToken new StableAccessToken // NewStableAccessToken new StableAccessToken
@@ -117,6 +118,7 @@ func NewStableAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.C
appSecret: appSecret, appSecret: appSecret,
cache: cache, cache: cache,
cacheKeyPrefix: cacheKeyPrefix, cacheKeyPrefix: cacheKeyPrefix,
accessTokenLock: new(sync.Mutex),
} }
} }
@@ -130,7 +132,20 @@ func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessT
// 先从cache中取 // 先从cache中取
accessTokenCacheKey := fmt.Sprintf("%s_stable_access_token_%s", ak.cacheKeyPrefix, ak.appID) accessTokenCacheKey := fmt.Sprintf("%s_stable_access_token_%s", ak.cacheKeyPrefix, ak.appID)
if val := ak.cache.Get(accessTokenCacheKey); val != nil { if val := ak.cache.Get(accessTokenCacheKey); val != nil {
return val.(string), nil if accessToken = val.(string); accessToken != "" {
return
}
}
// 加上lock是为了防止在并发获取token时cache刚好失效导致从微信服务器上获取到不同token
ak.accessTokenLock.Lock()
defer ak.accessTokenLock.Unlock()
// 双检,防止重复从微信服务器获取
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
if accessToken = val.(string); accessToken != "" {
return
}
} }
// cache失效从微信服务器获取 // cache失效从微信服务器获取