From b8c44c9b1ebf2acd0fe4c9bc908db55a2105a262 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=B6=9B?= Date: Fri, 12 Aug 2022 11:18:20 +0800 Subject: [PATCH] =?UTF-8?q?enhance(cache):=E5=A2=9E=E5=8A=A0=E4=B8=A4?= =?UTF-8?q?=E4=B8=AA=E7=94=A8=E4=BA=8E=E7=94=9F=E6=88=90=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E9=94=AE=E7=9A=84=E5=B7=A5=E5=85=B7=E5=87=BD=E6=95=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cache/abstract.go | 12 ++++++++++++ cache/session.go | 18 ++++++++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) 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) }