gredis_instance.go 934 B

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright 2017 gf Author(https://github.com/gogf/gf). 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 "github.com/gogf/gf/container/gmap"
  8. var (
  9. // Instance map
  10. instances = gmap.NewStrAnyMap(true)
  11. )
  12. // Instance returns an instance of redis client with specified group.
  13. // The <name> param is unnecessary, if <name> is not passed,
  14. // it returns a redis instance with default configuration group.
  15. func Instance(name ...string) *Redis {
  16. group := DefaultGroupName
  17. if len(name) > 0 && name[0] != "" {
  18. group = name[0]
  19. }
  20. v := instances.GetOrSetFuncLock(group, func() interface{} {
  21. if config, ok := GetConfig(group); ok {
  22. r := New(config)
  23. r.group = group
  24. return r
  25. }
  26. return nil
  27. })
  28. if v != nil {
  29. return v.(*Redis)
  30. }
  31. return nil
  32. }