gredis_instance.go 1.1 KB

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