hcmp/dbop/selfcache.go
2024-07-31 15:47:18 +08:00

67 lines
1.3 KiB
Go

package dbop
import (
"encoding/json"
"time"
"github.com/shockliu/logger"
)
const (
selfkeyhead = "sjwx:"
)
type SelfCache struct {
Prefix string
}
// NewMemory create new memcache
func NewSelfCache(key string) *SelfCache {
return &SelfCache{Prefix: selfkeyhead + key}
}
// Get return cached value
func (c *SelfCache) Get(key string) any {
key = c.Prefix + key
s, err := RDb.Get(key).Result()
if err != nil {
return nil
}
var reply any
if err = json.Unmarshal([]byte(s), &reply); err != nil {
return nil
}
logger.Debugf("微信小程序获取access_token[%v]\n", reply)
return reply
}
// IsExist check value exists in memcache.
func (c *SelfCache) IsExist(key string) bool {
key = c.Prefix + key
a := RDb.Exists(key)
logger.Debugf("微信小程序确认access_token是否存在%d\n", a.Val())
return a.Val() > 0
}
// Set cached value with key and expire time.
func (c *SelfCache) Set(key string, val any, timeout time.Duration) (err error) {
key = c.Prefix + key
var data []byte
if data, err = json.Marshal(val); err != nil {
return
}
RDb.Set(key, data, timeout)
logger.Debugf("微信小程序确认access_token保存[%s]\n", data)
return
}
// deleteKey
func (c *SelfCache) Delete(key string) (err error) {
key = c.Prefix + key
RDb.Del(key)
logger.Debugf("微信小程序删除access_token\n")
return nil
}