gins_redis.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 gins
  7. import (
  8. "fmt"
  9. "github.com/gogf/gf/database/gredis"
  10. "github.com/gogf/gf/util/gconv"
  11. "github.com/gogf/gf/util/gutil"
  12. )
  13. const (
  14. frameCoreComponentNameRedis = "gf.core.component.redis"
  15. configNodeNameRedis = "redis"
  16. )
  17. // Redis returns an instance of redis client with specified configuration group name.
  18. func Redis(name ...string) *gredis.Redis {
  19. config := Config()
  20. group := gredis.DefaultGroupName
  21. if len(name) > 0 && name[0] != "" {
  22. group = name[0]
  23. }
  24. instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameRedis, group)
  25. result := instances.GetOrSetFuncLock(instanceKey, func() interface{} {
  26. // If already configured, it returns the redis instance.
  27. if _, ok := gredis.GetConfig(group); ok {
  28. return gredis.Instance(group)
  29. }
  30. // Or else, it parses the default configuration file and returns a new redis instance.
  31. var m map[string]interface{}
  32. if _, v := gutil.MapPossibleItemByKey(Config().GetMap("."), configNodeNameRedis); v != nil {
  33. m = gconv.Map(v)
  34. }
  35. if len(m) > 0 {
  36. if v, ok := m[group]; ok {
  37. redisConfig, err := gredis.ConfigFromStr(gconv.String(v))
  38. if err != nil {
  39. panic(err)
  40. }
  41. return gredis.New(redisConfig)
  42. } else {
  43. panic(fmt.Sprintf(`configuration for redis not found for group "%s"`, group))
  44. }
  45. } else {
  46. filepath, err := config.GetFilePath()
  47. if err != nil {
  48. panic(err)
  49. }
  50. panic(fmt.Sprintf(
  51. `incomplete configuration for redis: "redis" node not found in config file "%s"`,
  52. filepath,
  53. ))
  54. }
  55. return nil
  56. })
  57. if result != nil {
  58. return result.(*gredis.Redis)
  59. }
  60. return nil
  61. }