Skip to content

Commit 6b487a4

Browse files
committed
feat:增加singleFlight并发控制jwt颁发
1 parent 39badd5 commit 6b487a4

File tree

3 files changed

+18
-5
lines changed

3 files changed

+18
-5
lines changed

server/global/global.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package global
33
import (
44
"gin-vue-admin/utils/timer"
55

6+
"golang.org/x/sync/singleflight"
7+
68
"go.uber.org/zap"
79

810
"gin-vue-admin/config"
@@ -18,6 +20,7 @@ var (
1820
GVA_CONFIG config.Server
1921
GVA_VP *viper.Viper
2022
//GVA_LOG *oplogging.Logger
21-
GVA_LOG *zap.Logger
22-
GVA_Timer timer.Timer = timer.NewTimerTask()
23+
GVA_LOG *zap.Logger
24+
GVA_Timer timer.Timer = timer.NewTimerTask()
25+
GVA_Concurrency_Control = &singleflight.Group{}
2326
)

server/go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ require (
5151
github.com/unrolled/secure v1.0.7
5252
go.uber.org/zap v1.10.0
5353
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect
54+
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
5455
golang.org/x/tools v0.0.0-20200324003944-a576cf524670 // indirect
5556
google.golang.org/protobuf v1.24.0 // indirect
5657
gopkg.in/ini.v1 v1.55.0 // indirect

server/middleware/jwt.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@ import (
77
"gin-vue-admin/model/request"
88
"gin-vue-admin/model/response"
99
"gin-vue-admin/service"
10+
"strconv"
11+
"time"
12+
1013
"github.com/dgrijalva/jwt-go"
1114
"github.com/gin-gonic/gin"
1215
"go.uber.org/zap"
13-
"strconv"
14-
"time"
1516
)
1617

1718
func JWTAuth() gin.HandlerFunc {
@@ -48,7 +49,7 @@ func JWTAuth() gin.HandlerFunc {
4849
}
4950
if claims.ExpiresAt-time.Now().Unix() < claims.BufferTime {
5051
claims.ExpiresAt = time.Now().Unix() + global.GVA_CONFIG.JWT.ExpiresTime
51-
newToken, _ := j.CreateToken(*claims)
52+
newToken, _ := j.CreateTokenByOldToken(token, *claims)
5253
newClaims, _ := j.ParseToken(newToken)
5354
c.Header("new-token", newToken)
5455
c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt, 10))
@@ -91,6 +92,14 @@ func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
9192
return token.SignedString(j.SigningKey)
9293
}
9394

95+
// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
96+
func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
97+
v, err, _ := global.GVA_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
98+
return j.CreateToken(claims)
99+
})
100+
return v.(string), err
101+
}
102+
94103
// 解析 token
95104
func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
96105
token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {

0 commit comments

Comments
 (0)