gf/frame/gins/gins_redis.go

75 lines
2.1 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
2020-02-23 20:25:55 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gins
import (
"context"
2020-02-23 20:25:55 +08:00
"fmt"
2021-11-13 23:23:55 +08:00
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/internal/intlog"
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gutil"
2020-02-23 20:25:55 +08:00
)
const (
2020-12-14 13:26:48 +08:00
frameCoreComponentNameRedis = "gf.core.component.redis"
configNodeNameRedis = "redis"
2020-02-23 20:25:55 +08:00
)
// Redis returns an instance of redis client with specified configuration group name.
// Note that it panics if any error occurs duration instance creating.
2020-02-23 20:25:55 +08:00
func Redis(name ...string) *gredis.Redis {
var (
err error
ctx = context.Background()
group = gredis.DefaultGroupName
)
2020-02-23 20:25:55 +08:00
if len(name) > 0 && name[0] != "" {
group = name[0]
}
2020-12-14 13:26:48 +08:00
instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameRedis, group)
result := localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
2020-02-23 20:25:55 +08:00
// If already configured, it returns the redis instance.
if _, ok := gredis.GetConfig(group); ok {
return gredis.Instance(group)
}
if Config().Available(ctx) {
var (
configMap map[string]interface{}
redisConfig *gredis.Config
redisClient *gredis.Redis
)
if configMap, err = Config().Data(ctx); err != nil {
intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
}
if _, v := gutil.MapPossibleItemByKey(configMap, configNodeNameRedis); v != nil {
configMap = gconv.Map(v)
}
if len(configMap) > 0 {
if v, ok := configMap[group]; ok {
if redisConfig, err = gredis.ConfigFromMap(gconv.Map(v)); err != nil {
panic(err)
}
2021-09-23 19:12:02 +08:00
}
intlog.Printf(ctx, `missing configuration for redis group "%s"`, group)
2020-02-23 20:25:55 +08:00
} else {
intlog.Printf(ctx, `missing configuration for redis: "redis" node not found`)
}
if redisClient, err = gredis.New(redisConfig); err != nil {
panic(err)
2020-02-23 20:25:55 +08:00
}
return redisClient
2020-02-23 20:25:55 +08:00
}
return nil
})
if result != nil {
return result.(*gredis.Redis)
}
return nil
}