12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- package config
- import (
- "encoding/json"
- "gadmin/internal/gorm/model"
- "gadmin/internal/gorm/query"
- "github.com/sirupsen/logrus"
- "gorm.io/gorm/clause"
- "time"
- )
- func GetCache(key string) string {
- var models *model.Cache
- DB.Where("`key` = ?", key).First(&models)
- if models == nil {
- return ""
- }
- if models.ExpiAt > 0 && models.ExpiAt < time.Now().Unix() {
- return ""
- }
- return models.Value
- }
- func GetCacheScan(key string, v any) (err error) {
- data := GetCache(key)
- if data == "" {
- return
- }
- return json.Unmarshal([]byte(data), v)
- }
- func SetCache(key string, value interface{}, ttl ...int64) {
- marshal, err := json.Marshal(value)
- if err != nil {
- logrus.Warnf("SetCache Marshal err:%+v, value:%+v", err, value)
- return
- }
- var models = new(model.Cache)
- models.Key = key
- models.Value = string(marshal)
- if len(ttl) > 0 && ttl[0] > 0 {
- models.ExpiAt = ttl[0]
- }
- if err = query.Use(DB).Cache.Clauses(clause.OnConflict{UpdateAll: true}).Create(models); err != nil {
- logrus.Errorf("SetCache err: %v", err)
- }
- }
|