gins_redis.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "context"
  9. "fmt"
  10. "github.com/gogf/gf/v2/database/gredis"
  11. "github.com/gogf/gf/v2/internal/consts"
  12. "github.com/gogf/gf/v2/internal/intlog"
  13. "github.com/gogf/gf/v2/util/gconv"
  14. "github.com/gogf/gf/v2/util/gutil"
  15. )
  16. const (
  17. frameCoreComponentNameRedis = "gf.core.component.redis"
  18. )
  19. // Redis returns an instance of redis client with specified configuration group name.
  20. // Note that it panics if any error occurs duration instance creating.
  21. func Redis(name ...string) *gredis.Redis {
  22. var (
  23. err error
  24. ctx = context.Background()
  25. group = gredis.DefaultGroupName
  26. )
  27. if len(name) > 0 && name[0] != "" {
  28. group = name[0]
  29. }
  30. instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameRedis, group)
  31. result := localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
  32. // If already configured, it returns the redis instance.
  33. if _, ok := gredis.GetConfig(group); ok {
  34. return gredis.Instance(group)
  35. }
  36. if Config().Available(ctx) {
  37. var (
  38. configMap map[string]interface{}
  39. redisConfig *gredis.Config
  40. redisClient *gredis.Redis
  41. )
  42. if configMap, err = Config().Data(ctx); err != nil {
  43. intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
  44. }
  45. if _, v := gutil.MapPossibleItemByKey(configMap, consts.ConfigNodeNameRedis); v != nil {
  46. configMap = gconv.Map(v)
  47. }
  48. if len(configMap) > 0 {
  49. if v, ok := configMap[group]; ok {
  50. if redisConfig, err = gredis.ConfigFromMap(gconv.Map(v)); err != nil {
  51. panic(err)
  52. }
  53. } else {
  54. intlog.Printf(ctx, `missing configuration for redis group "%s"`, group)
  55. }
  56. } else {
  57. intlog.Print(ctx, `missing configuration for redis: "redis" node not found`)
  58. }
  59. if redisClient, err = gredis.New(redisConfig); err != nil {
  60. panic(err)
  61. }
  62. return redisClient
  63. }
  64. return nil
  65. })
  66. if result != nil {
  67. return result.(*gredis.Redis)
  68. }
  69. return nil
  70. }