enhance(cache):为缓存增加60秒内的随机秒数,以避免缓存雪崩。

This commit is contained in:
徐涛 2022-09-06 12:28:06 +08:00
parent ae056f612a
commit bd1033ac47

4
cache/abstract.go vendored
View File

@ -3,6 +3,7 @@ package cache
import ( import (
"electricity_bill_calc/global" "electricity_bill_calc/global"
"fmt" "fmt"
"math/rand"
"strings" "strings"
"time" "time"
@ -23,9 +24,10 @@ const (
func Cache[T interface{}](key string, value *T, expires time.Duration) error { func Cache[T interface{}](key string, value *T, expires time.Duration) error {
var err error var err error
if expires > 0 { if expires > 0 {
realExpires := expires + time.Duration(rand.Int63n(60))*time.Second
setCmd := global.RedisConn.B().Set(). setCmd := global.RedisConn.B().Set().
Key(key).Value(rueidis.JSON(value)). Key(key).Value(rueidis.JSON(value)).
ExSeconds(int64(expires.Seconds())). ExSeconds(int64(realExpires.Seconds())).
Build() Build()
err = global.RedisConn.Do(global.Ctx, setCmd).Error() err = global.RedisConn.Do(global.Ctx, setCmd).Error()
} else { } else {