Browse Source

get wechat access token with lock

ls 3 years ago
parent
commit
2c7f57183d
4 changed files with 12 additions and 4 deletions
  1. 1 1
      go.mod
  2. 4 1
      wechat/client.go
  3. 1 1
      wechat/const.go
  4. 6 1
      wechat/structure.go

+ 1 - 1
go.mod

@@ -7,7 +7,7 @@ require (
 	github.com/go-sql-driver/mysql v1.5.0
 	github.com/golang/protobuf v1.3.5
 	github.com/jmoiron/sqlx v1.2.0
-	github.com/lib/pq v1.7.0
+	github.com/lib/pq v1.8.0
 	github.com/ugorji/go v1.1.7
 	github.com/ugorji/go/codec v1.1.7
 	golang.org/x/net v0.0.0-20190923162816-aa69164e4478

+ 4 - 1
wechat/client.go

@@ -4,6 +4,7 @@ import (
 	"errors"
 	"fmt"
 	"net/url"
+	"sync"
 	"time"
 
 	"git.chuangxin1.com/cx/myth"
@@ -19,13 +20,15 @@ func NewClient(appID, appSecret, token, encodingAESKey string) *Client {
 	if v, ok := cache.Load(key); ok {
 		return v.(*Client)
 	}
-	c := &Client{AppID: appID, AppSecret: appSecret, Token: token, EncodingAESKey: encodingAESKey}
+	c := &Client{AppID: appID, AppSecret: appSecret, Token: token, EncodingAESKey: encodingAESKey, ReadLock: new(sync.Mutex)}
 	cache.Store(key, c)
 	return c
 }
 
 // getToken get token
 func (wc *Client) getToken() (token string, err error) {
+	wc.ReadLock.Lock()
+	defer wc.ReadLock.Unlock()
 	now := time.Now().Unix()
 	if wc.LastTokenTime > 0 {
 		if now-wc.LastTokenTime < TokenExpires {

+ 1 - 1
wechat/const.go

@@ -2,7 +2,7 @@ package wechat
 
 const (
 	// TokenExpires token expires time 1 hours
-	TokenExpires = 60 * 60
+	TokenExpires = 90 * 60
 	// TicketExpires ticket expires time 1 hours
 	TicketExpires = 60 * 60
 

+ 6 - 1
wechat/structure.go

@@ -1,6 +1,9 @@
 package wechat
 
-import "encoding/xml"
+import (
+	"encoding/xml"
+	"sync"
+)
 
 // FormSignature signature
 type FormSignature struct {
@@ -196,6 +199,8 @@ type Client struct {
 	Token          string `json:"token"`
 	EncodingAESKey string `json:"encodingaeskey"`
 
+	ReadLock *sync.Mutex
+
 	AccessToken   string
 	LastTokenTime int64