main
lizifeng 2023-05-17 19:56:42 +08:00
parent 275652416b
commit 7c499ad86a
2 changed files with 12 additions and 22 deletions

View File

@ -56,11 +56,11 @@ func Instance(key ...string) *MyRedis {
return instance
}
func NewDefault(config *Config) (*MyRedis, error) {
return New(DefaultKey, config)
func InitDefault(config *Config) error {
return Init(DefaultKey, config)
}
func New(key string, config *Config) (*MyRedis, error) {
func Init(key string, config *Config) error {
var (
maxConnAge, _ = time.ParseDuration(DefaultConfig.MaxConnAge)
idleTimeout, _ = time.ParseDuration(DefaultConfig.IdleTimeout)
@ -77,7 +77,7 @@ func New(key string, config *Config) (*MyRedis, error) {
if config.MaxConnAge != "" {
t, err := time.ParseDuration(config.MaxConnAge)
if err != nil {
return nil, fmt.Errorf("parse MaxConnAge err: %s\n", err)
return fmt.Errorf("parse MaxConnAge err: %s\n", err)
}
maxConnAge = t
@ -86,7 +86,7 @@ func New(key string, config *Config) (*MyRedis, error) {
if config.IdleTimeout != "" {
t, err := time.ParseDuration(config.IdleTimeout)
if err != nil {
return nil, fmt.Errorf("parse IdleTimeout err: %s\n", err)
return fmt.Errorf("parse IdleTimeout err: %s\n", err)
}
idleTimeout = t
@ -107,11 +107,11 @@ func New(key string, config *Config) (*MyRedis, error) {
rd.Client = client
ping := rd.Client.Ping(ctx)
if ping.Err() != nil {
return nil, fmt.Errorf("connet redis err: %s", ping.Err())
return fmt.Errorf("connet redis err: %s", ping.Err())
}
instanceMap[key] = rd
return rd, nil
return nil
}
// GetSimple 通用get
@ -165,16 +165,6 @@ func (r *MyRedis) SetJson(key string, value interface{}, t ...time.Duration) (st
return r.Client.Set(ctx, key, v, t2).Result()
}
func (r *MyRedis) Close() {
if r.Client != nil {
r.Client.Close()
}
}
func (r *MyRedis) GetConn() *redis.Client {
return r.Client
}
func Close(key string) {
Instance(key).Client.Close()
}

View File

@ -8,8 +8,8 @@ import (
)
func TestRedis(t *testing.T) {
redis, err := NewDefault(&Config{
Addr: "127.0.0.1:6379",
err := InitDefault(&Config{
Addr: "192.168.244.128:6379",
Password: "",
DB: 15,
PoolSize: 16,
@ -21,16 +21,16 @@ func TestRedis(t *testing.T) {
fmt.Println(err)
return
}
defer redis.Close()
defer CloseAll()
set, err := redis.Set(context.Background(), "name", "qwe123", time.Minute).Result()
set, err := Instance().Set(context.Background(), "name", "qwe123", time.Minute).Result()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(set)
get, err := redis.Get(context.Background(), "name").Result()
get, err := Instance().Get(context.Background(), "name").Result()
if err != nil {
fmt.Println(err)
return