redis.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package redis
  4. import (
  5. "fmt"
  6. "github.com/go-redis/redis"
  7. )
  8. type Redis struct {
  9. cluster bool
  10. client *redis.Client
  11. cclient *redis.ClusterClient
  12. }
  13. var (
  14. errRedis = fmt.Errorf("redis is nil")
  15. errRedisClient = fmt.Errorf("redis client is nil")
  16. errRedisCClient = fmt.Errorf("redis cclient is nil")
  17. )
  18. func New(addrs []string, passwd string, db int,
  19. poolSize, minIdleConns, maxRetries int, cluster bool) *Redis {
  20. if len(addrs) == 0 {
  21. panic("Redis's addrs is empty.")
  22. }
  23. r := &Redis{cluster: cluster}
  24. if cluster {
  25. r.cclient = redis.NewClusterClient(&redis.ClusterOptions{
  26. Addrs: addrs,
  27. Password: passwd,
  28. PoolSize: poolSize,
  29. MinIdleConns: minIdleConns,
  30. MaxRetries: maxRetries,
  31. })
  32. // check if redis server is ok.
  33. if _, err := r.cclient.Ping().Result(); err != nil {
  34. panic(err)
  35. }
  36. } else {
  37. r.client = redis.NewClient(&redis.Options{
  38. Addr: addrs[0],
  39. Password: passwd,
  40. DB: db,
  41. PoolSize: poolSize,
  42. MinIdleConns: minIdleConns,
  43. MaxRetries: maxRetries,
  44. })
  45. // check if redis server is ok.
  46. if _, err := r.client.Ping().Result(); err != nil {
  47. panic(err)
  48. }
  49. }
  50. return r
  51. }
  52. // Close 关闭redis
  53. func (p *Redis) Close() {
  54. if p != nil {
  55. if p.cluster {
  56. if p.cclient != nil {
  57. p.cclient.Close()
  58. }
  59. } else {
  60. if p.client != nil {
  61. p.client.Close()
  62. }
  63. }
  64. }
  65. }