gredis.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gredis provides convenient client for redis server.
  7. //
  8. // Redis Client.
  9. //
  10. // Redis Commands Official: https://redis.io/commands
  11. //
  12. // Redis Chinese Documentation: http://redisdoc.com/
  13. package gredis
  14. import (
  15. "github.com/gogf/gf/v2/errors/gcode"
  16. "github.com/gogf/gf/v2/errors/gerror"
  17. )
  18. // AdapterFunc is the function creating redis adapter.
  19. type AdapterFunc func(config *Config) Adapter
  20. var (
  21. // defaultAdapterFunc is the default adapter function creating redis adapter.
  22. defaultAdapterFunc AdapterFunc = func(config *Config) Adapter {
  23. return nil
  24. }
  25. )
  26. // New creates and returns a redis client.
  27. // It creates a default redis adapter of go-redis.
  28. func New(config ...*Config) (*Redis, error) {
  29. var (
  30. usedConfig *Config
  31. usedAdapter Adapter
  32. )
  33. if len(config) > 0 && config[0] != nil {
  34. // Redis client with go redis implements adapter from given configuration.
  35. usedConfig = config[0]
  36. usedAdapter = defaultAdapterFunc(config[0])
  37. } else if configFromGlobal, ok := GetConfig(); ok {
  38. // Redis client with go redis implements adapter from package configuration.
  39. usedConfig = configFromGlobal
  40. usedAdapter = defaultAdapterFunc(configFromGlobal)
  41. }
  42. if usedConfig == nil {
  43. return nil, gerror.NewCode(
  44. gcode.CodeInvalidConfiguration,
  45. `no configuration found for creating Redis client`,
  46. )
  47. }
  48. if usedAdapter == nil {
  49. return nil, gerror.NewCode(
  50. gcode.CodeNecessaryPackageNotImport,
  51. errorNilAdapter,
  52. )
  53. }
  54. redis := &Redis{
  55. config: usedConfig,
  56. localAdapter: usedAdapter,
  57. }
  58. return redis.initGroup(), nil
  59. }
  60. // NewWithAdapter creates and returns a redis client with given adapter.
  61. func NewWithAdapter(adapter Adapter) (*Redis, error) {
  62. if adapter == nil {
  63. return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `adapter cannot be nil`)
  64. }
  65. redis := &Redis{localAdapter: adapter}
  66. return redis.initGroup(), nil
  67. }
  68. // RegisterAdapterFunc registers default function creating redis adapter.
  69. func RegisterAdapterFunc(adapterFunc AdapterFunc) {
  70. defaultAdapterFunc = adapterFunc
  71. }