feat(cache):增加向redis保存用户会话的函数。

This commit is contained in:
徐涛 2022-08-11 17:33:32 +08:00
parent 230e366a7f
commit 5ebf6b0431
2 changed files with 53 additions and 0 deletions

42
cache/session.go vendored Normal file
View File

@ -0,0 +1,42 @@
package cache
import (
"electricity_bill_calc/global"
"electricity_bill_calc/model"
"fmt"
"time"
"github.com/go-redis/redis/v8"
"github.com/vmihailenco/msgpack/v5"
)
func CacheSession(session *model.Session) error {
key := fmt.Sprintf("session:%s", session.Token)
serializedSession, err := msgpack.Marshal(session)
if err != nil {
return err
}
validRemains := time.Until(session.ExpiresAt)
cmd := global.RedisConn.SetNX(global.Ctx, key, serializedSession, validRemains)
return cmd.Err()
}
func RetreiveSession(token string) (*model.Session, error) {
key := fmt.Sprintf("session:%s", token)
result, err := global.RedisConn.Get(global.Ctx, key).Result()
if err != nil {
if err == redis.Nil {
return nil, nil
} else {
return nil, err
}
}
session := &model.Session{}
err = msgpack.Unmarshal([]byte(result), session)
if err != nil {
return nil, err
}
return session, nil
}

11
model/session.go Normal file
View File

@ -0,0 +1,11 @@
package model
import "time"
type Session struct {
Uid string `json:"uid"`
Name string `json:"name"`
Type int8 `json:"type"`
Token string `json:"token"`
ExpiresAt time.Time `json:"expiresAt"`
}