mysql_cache.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package config
  2. import (
  3. "encoding/json"
  4. "gadmin/internal/gorm/model"
  5. "gadmin/internal/gorm/query"
  6. "github.com/sirupsen/logrus"
  7. "gorm.io/gorm/clause"
  8. "time"
  9. )
  10. func GetCache(key string) string {
  11. var models *model.Cache
  12. DB.Where("`key` = ?", key).First(&models)
  13. if models == nil {
  14. return ""
  15. }
  16. if models.ExpiAt > 0 && models.ExpiAt < time.Now().Unix() {
  17. return ""
  18. }
  19. return models.Value
  20. }
  21. func GetCacheScan(key string, v any) (err error) {
  22. data := GetCache(key)
  23. if data == "" {
  24. return
  25. }
  26. return json.Unmarshal([]byte(data), v)
  27. }
  28. func SetCache(key string, value interface{}, ttl ...int64) {
  29. marshal, err := json.Marshal(value)
  30. if err != nil {
  31. logrus.Warnf("SetCache Marshal err:%+v, value:%+v", err, value)
  32. return
  33. }
  34. var models = new(model.Cache)
  35. models.Key = key
  36. models.Value = string(marshal)
  37. if len(ttl) > 0 && ttl[0] > 0 {
  38. models.ExpiAt = ttl[0]
  39. }
  40. if err = query.Use(DB).Cache.Clauses(clause.OnConflict{UpdateAll: true}).Create(models); err != nil {
  41. logrus.Errorf("SetCache err: %v", err)
  42. }
  43. }