Skip to content

Commit

Permalink
perf(yxy): 使用singleflight优化电费AuthToken获取逻辑,防止缓存击穿
Browse files Browse the repository at this point in the history
  • Loading branch information
XiMo-210 committed Nov 16, 2024
1 parent 7fae7d1 commit c4dcfb1
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
26 changes: 19 additions & 7 deletions app/services/yxyServices/cacheService.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import (
"time"
r "wejh-go/config/redis"

"golang.org/x/sync/singleflight"

"github.com/go-redis/redis/v8"
)

var ctx = context.Background()
var (
ctx = context.Background()
g singleflight.Group
)

func GetElecRoomStrConcat(token, campus, yxyUid string) (*string, error) {
cacheKey := "elec:room_str_concat:" + campus + ":" + yxyUid
Expand All @@ -33,15 +38,22 @@ func GetElecAuthToken(yxyUid string) (*string, error) {
cacheKey := "elec:auth_token:" + yxyUid
cachedToken, err := r.RedisClient.Get(ctx, cacheKey).Result()
if err == redis.Nil {
token, err := Auth(yxyUid)
if err != nil {
return nil, err
}
err = r.RedisClient.Set(ctx, cacheKey, *token, 7*24*time.Hour).Err()
// 使用 singleflight 防止缓存击穿
token, err, _ := g.Do(cacheKey, func() (interface{}, error) {
t, e := Auth(yxyUid)
if e != nil {
return nil, e
}
e = r.RedisClient.Set(ctx, cacheKey, *t, 7*24*time.Hour).Err()
if e != nil {
return nil, e
}
return t, nil
})
if err != nil {
return nil, err
}
return token, nil
return token.(*string), nil
} else if err != nil {
return nil, err
}
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ require (
github.com/ugorji/go v1.2.5 // indirect
github.com/xuri/excelize/v2 v2.8.0
go.opentelemetry.io/otel v0.20.0 // indirect
golang.org/x/sync v0.1.0
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gorm.io/driver/mysql v1.0.6
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand Down

0 comments on commit c4dcfb1

Please sign in to comment.