gredis_instance.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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
  7. import (
  8. "context"
  9. "github.com/gogf/gf/v2/container/gmap"
  10. "github.com/gogf/gf/v2/internal/intlog"
  11. )
  12. var (
  13. localInstances = gmap.NewStrAnyMap(true)
  14. )
  15. // Instance returns an instance of redis client with specified group.
  16. // The `name` param is unnecessary, if `name` is not passed,
  17. // it returns a redis instance with default configuration group.
  18. func Instance(name ...string) *Redis {
  19. group := DefaultGroupName
  20. if len(name) > 0 && name[0] != "" {
  21. group = name[0]
  22. }
  23. v := localInstances.GetOrSetFuncLock(group, func() interface{} {
  24. if config, ok := GetConfig(group); ok {
  25. r, err := New(config)
  26. if err != nil {
  27. intlog.Errorf(context.TODO(), `%+v`, err)
  28. return nil
  29. }
  30. return r
  31. }
  32. return nil
  33. })
  34. if v != nil {
  35. return v.(*Redis)
  36. }
  37. return nil
  38. }