redis_client.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package cache
  2. import (
  3. "context"
  4. "time"
  5. )
  6. type Redis struct {
  7. DB int `mapstructure:"db" json:"db" yaml:"db"`
  8. Addr string `mapstructure:"addr" json:"addr" yaml:"addr"`
  9. Password string `mapstructure:"password" json:"password" yaml:"password"`
  10. PoolSize int `mapstructure:"pool-size" json:"pool-size" yaml:"pool-size"`
  11. }
  12. func SetCache(key string, value interface{}, expiration time.Duration) error {
  13. err := Instance().Set(context.Background(), key, value, expiration).Err()
  14. if err != nil {
  15. return err
  16. }
  17. return nil
  18. }
  19. func GetCache(key string) (interface{}, error) {
  20. return Instance().Get(context.Background(), key).Result()
  21. }
  22. func DeleteCache(key string) (int64, error) {
  23. return Instance().Del(context.Background(), key).Result()
  24. }
  25. func GetCacheString(key string) (string, error) {
  26. value, err := GetCacheBytes(key)
  27. if err != nil {
  28. return "", err
  29. }
  30. return string(value), nil
  31. }
  32. func GetCacheBytes(key string) ([]byte, error) {
  33. return Instance().Get(context.Background(), key).Bytes()
  34. }
  35. func GetCacheUint(key string) (uint64, error) {
  36. return Instance().Get(context.Background(), key).Uint64()
  37. }