1
0
mirror of https://github.com/silenceper/wechat.git synced 2026-02-04 12:52:27 +08:00

Update default_access_token.go (#805)

* Update default_access_token.go

微信获取稳定版token,只有不等于空字符串的情况下才会返回access_token信息,未空的情况,继续调去微信服务

* 微信稳定性获取 access_token 接口,添加防止并发性获取 access_token 和多次微信服务获取代码

---------

Co-authored-by: w_yangyili <w_yangyili@xiwang.com>
This commit is contained in:
yangyl12345
2024-11-26 12:13:49 +08:00
committed by GitHub
parent 3fbe8634d9
commit a571bf3546

View File

@@ -101,10 +101,11 @@ func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (access
// 不强制更新access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存避免access_token争抢 // 不强制更新access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存避免access_token争抢
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html // https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
type StableAccessToken struct { type StableAccessToken struct {
appID string appID string
appSecret string appSecret string
cacheKeyPrefix string cacheKeyPrefix string
cache cache.Cache cache cache.Cache
accessTokenLock *sync.Mutex
} }
// NewStableAccessToken new StableAccessToken // NewStableAccessToken new StableAccessToken
@@ -113,10 +114,11 @@ func NewStableAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.C
panic("cache is need") panic("cache is need")
} }
return &StableAccessToken{ return &StableAccessToken{
appID: appID, appID: appID,
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失效从微信服务器获取