redis_client.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package redis_client
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "github.com/redis/go-redis/v9"
  6. "time"
  7. )
  8. type Client struct {
  9. redisClient *redis.Client
  10. }
  11. func NewClient(address string, userName string, password string, db int) (*Client, error) {
  12. if address == "" {
  13. return nil, errors.New("redis address不能为空")
  14. }
  15. return &Client{redisClient: redis.NewClient(&redis.Options{
  16. Addr: address,
  17. Username: userName,
  18. Password: password,
  19. DB: db,
  20. })}, nil
  21. }
  22. func Destroy(client *Client) error {
  23. if client == nil || client.redisClient == nil {
  24. return nil
  25. }
  26. err := client.redisClient.Close()
  27. if err != nil {
  28. return err
  29. }
  30. client.redisClient = nil
  31. return nil
  32. }
  33. func (client *Client) Set(key string, value any, expireSec int64) error {
  34. cmd := client.redisClient.Set(context.Background(), key, value, time.Second*time.Duration(expireSec))
  35. if cmd.Err() != nil {
  36. return cmd.Err()
  37. }
  38. return nil
  39. }
  40. func (client *Client) Get(key string) (any, error) {
  41. cmd := client.redisClient.Get(context.Background(), key)
  42. if cmd.Err() != nil {
  43. if cmd.Err().Error() == redis.Nil.Error() {
  44. return nil, nil
  45. }
  46. return nil, cmd.Err()
  47. }
  48. return cmd.Val(), nil
  49. }
  50. func (client *Client) GetMulti(keys []string) (map[string]any, error) {
  51. result := make(map[string]any)
  52. for _, key := range keys {
  53. cmd := client.redisClient.Get(context.Background(), key)
  54. if cmd.Err() != nil {
  55. if cmd.Err().Error() == redis.Nil.Error() {
  56. result[key] = nil
  57. continue
  58. }
  59. return nil, cmd.Err()
  60. }
  61. result[key] = cmd.Val()
  62. }
  63. return result, nil
  64. }