52 lines
933 B
Go
52 lines
933 B
Go
|
package cache
|
||
|
|
||
|
import (
|
||
|
"MossChat/config"
|
||
|
"MossChat/logger"
|
||
|
"MossChat/utils"
|
||
|
"github.com/go-redis/redis"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
var DB *redis.Client
|
||
|
|
||
|
func InitRedis() {
|
||
|
DB = redis.NewClient(&redis.Options{
|
||
|
Addr: config.REDIS_ADDR,
|
||
|
DB: 0,
|
||
|
})
|
||
|
_, err := DB.Ping().Result()
|
||
|
if err != nil {
|
||
|
logger.Log.Println("无法连接到Redis!")
|
||
|
panic(err)
|
||
|
}
|
||
|
logger.Log.Println("已加载redis!")
|
||
|
}
|
||
|
|
||
|
// GenerateToken 计算新的Token
|
||
|
func GenerateToken(uid int, duration time.Duration) error {
|
||
|
err := DB.Set(utils.ToTokenKey(utils.RandomString(16)), uid, duration).Err()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// 获取用户ID
|
||
|
func GetUidByToken(token string) (int, error) {
|
||
|
uid, err := DB.Get(utils.ToTokenKey(token)).Int()
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
return uid, nil
|
||
|
}
|
||
|
|
||
|
// 移除Token
|
||
|
func RemoveToken(token string) error {
|
||
|
err := DB.Del(utils.ToTokenKey(token)).Err()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|