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