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