This commit is contained in:
2023-03-20 20:41:36 +08:00
parent e807b9393c
commit 9c83b42ccd
4 changed files with 86 additions and 22 deletions

View File

@@ -8,6 +8,8 @@ import (
"time"
)
const DefaultKey = "default"
var (
DefaultConfig = &Config{
Addr: "127.0.0.1:6379",
@@ -18,11 +20,13 @@ var (
MaxConnAge: "1h",
IdleTimeout: "10m",
}
instanceMap = make(map[string]*MyRedis)
)
type (
MyRedis struct {
Redis *redis.Client
redis *redis.Client
ctx context.Context
}
@@ -37,7 +41,27 @@ type (
}
)
func New(config *Config) (*MyRedis, error) {
func Instance(key ...string) *MyRedis {
var key0 string
if len(key) > 0 {
key0 = key[0]
} else {
key0 = DefaultKey
}
instance, ok := instanceMap[key0]
if !ok {
panic(fmt.Errorf("%s not config", key))
}
return instance
}
func NewDefault(config *Config) (*MyRedis, error) {
return New(DefaultKey, config)
}
func New(key string, config *Config) (*MyRedis, error) {
var (
maxConnAge, _ = time.ParseDuration(DefaultConfig.MaxConnAge)
idleTimeout, _ = time.ParseDuration(DefaultConfig.IdleTimeout)
@@ -82,18 +106,19 @@ func New(config *Config) (*MyRedis, error) {
ctx := context.Background()
rd := &MyRedis{}
rd.ctx = ctx
rd.Redis = client
ping := rd.Redis.Ping(ctx)
rd.redis = client
ping := rd.redis.Ping(ctx)
if ping.Err() != nil {
return nil, fmt.Errorf("connet redis err: %s", ping.Err())
}
instanceMap[key] = rd
return rd, nil
}
// Get 通用get
func (r *MyRedis) Get(key string) (string, error) {
return r.Redis.Get(r.ctx, key).Result()
return r.redis.Get(r.ctx, key).Result()
}
// Set 通用set
@@ -102,12 +127,12 @@ func (r *MyRedis) Set(key string, value interface{}, t ...time.Duration) (string
if len(t) > 0 {
t2 = t[0]
}
return r.Redis.Set(r.ctx, key, value, t2).Result()
return r.redis.Set(r.ctx, key, value, t2).Result()
}
// GetJson json序列化
func (r *MyRedis) GetJson(key string) (interface{}, error) {
res := r.Redis.Get(r.ctx, key)
res := r.redis.Get(r.ctx, key)
if res.Err() != nil {
return nil, res.Err()
}
@@ -134,11 +159,15 @@ func (r *MyRedis) SetJson(key string, value interface{}, t ...time.Duration) (st
if err != nil {
return "", fmt.Errorf("set key:%s 序列化json失败", key)
}
return r.Redis.Set(r.ctx, key, v, t2).Result()
return r.redis.Set(r.ctx, key, v, t2).Result()
}
func (r *MyRedis) Close() {
if r.Redis != nil {
r.Redis.Close()
if r.redis != nil {
r.redis.Close()
}
}
func (r *MyRedis) Redis() *redis.Client {
return r.redis
}

View File

@@ -7,7 +7,7 @@ import (
)
func TestRedis(t *testing.T) {
redis, err := New(&Config{
redis, err := NewDefault(&Config{
Addr: "127.0.0.1:6379",
Password: "",
DB: 15,