diff --git a/cache/abstract.go b/cache/abstract.go index f8ae8ef..dc8cb9a 100644 --- a/cache/abstract.go +++ b/cache/abstract.go @@ -2,6 +2,8 @@ package cache import ( "electricity_bill_calc/global" + "fmt" + "strings" "time" "github.com/go-redis/redis/v8" @@ -56,3 +58,13 @@ func Delete(key string) (bool, error) { } return result > 0, nil } + +// 生成用于Redis存储的键 +func CacheKey(category string, ids ...string) string { + var b strings.Builder + b.WriteString(category) + for _, s := range ids { + fmt.Fprintf(&b, ":%s", s) + } + return b.String() +} diff --git a/cache/session.go b/cache/session.go index a656c09..4e4b179 100644 --- a/cache/session.go +++ b/cache/session.go @@ -3,25 +3,35 @@ package cache import ( "electricity_bill_calc/model" "fmt" + "strings" "time" ) +func SessionKey(keys ...string) string { + var b strings.Builder + b.WriteString("session") + for _, s := range keys { + fmt.Fprintf(&b, ":%s", s) + } + return b.String() +} + func CacheSession(session *model.Session) error { - key := fmt.Sprintf("session:%s", session.Token) + key := SessionKey(session.Token) return Cache(key, session, 2*time.Hour) } func RetreiveSession(token string) (*model.Session, error) { - key := fmt.Sprintf("session:%s", token) + key := SessionKey(token) return Retreive[model.Session](key) } func HasSession(token string) (bool, error) { - key := fmt.Sprintf("session:%s", token) + key := SessionKey(token) return Exists(key) } func ClearSession(token string) (bool, error) { - key := fmt.Sprintf("session:%s", token) + key := SessionKey(token) return Delete(key) }