golang-im聊天
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

48 lines
956 B

  1. package util
  2. import (
  3. "gim/pkg/logger"
  4. "time"
  5. "github.com/go-redis/redis"
  6. jsoniter "github.com/json-iterator/go"
  7. )
  8. type RedisUtil struct {
  9. client *redis.Client
  10. }
  11. func NewRedisUtil(client *redis.Client) *RedisUtil {
  12. return &RedisUtil{client: client}
  13. }
  14. // Set 将指定值设置到redis中,使用json的序列化方式
  15. func (u *RedisUtil) Set(key string, value interface{}, duration time.Duration) error {
  16. bytes, err := jsoniter.Marshal(value)
  17. if err != nil {
  18. logger.Sugar.Error(err)
  19. return err
  20. }
  21. err = u.client.Set(key, bytes, duration).Err()
  22. if err != nil {
  23. logger.Sugar.Error(err)
  24. return err
  25. }
  26. return nil
  27. }
  28. // Get 从redis中读取指定值,使用json的反序列化方式
  29. func (u *RedisUtil) Get(key string, value interface{}) error {
  30. bytes, err := u.client.Get(key).Bytes()
  31. if err != nil {
  32. return err
  33. }
  34. err = jsoniter.Unmarshal(bytes, value)
  35. if err != nil {
  36. logger.Sugar.Error(err)
  37. return err
  38. }
  39. return nil
  40. }