mycommon/myredis/redis.go

181 lines
3.5 KiB
Go

package myredis
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
jsoniter "github.com/json-iterator/go"
"time"
)
const DefaultKey = "default"
var (
DefaultConfig = &Config{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
PoolSize: 16,
MinIdleConn: 4,
MaxConnAge: "1h",
IdleTimeout: "10m",
}
instanceMap = make(map[string]*MyRedis)
)
type (
MyRedis struct {
*redis.Client
}
Config struct {
Addr string
Password string
DB int
PoolSize int
MinIdleConn int
MaxConnAge string
IdleTimeout string
}
)
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("redis %s not config", key0))
}
return instance
}
func InitDefault(config *Config) error {
return Init(DefaultKey, config)
}
func Init(key string, config *Config) error {
rd, err := New(config)
if err != nil {
return err
}
instanceMap[key] = rd
return nil
}
func New(config *Config) (*MyRedis, error) {
var (
maxConnAge, _ = time.ParseDuration(DefaultConfig.MaxConnAge)
idleTimeout, _ = time.ParseDuration(DefaultConfig.IdleTimeout)
)
if config.PoolSize <= 0 {
config.MinIdleConn = DefaultConfig.PoolSize
}
if config.MinIdleConn <= 0 {
config.MinIdleConn = DefaultConfig.MinIdleConn
}
if config.MaxConnAge != "" {
t, err := time.ParseDuration(config.MaxConnAge)
if err != nil {
return nil, fmt.Errorf("parse MaxConnAge err: %s\n", err)
}
maxConnAge = t
}
if config.IdleTimeout != "" {
t, err := time.ParseDuration(config.IdleTimeout)
if err != nil {
return nil, fmt.Errorf("parse IdleTimeout err: %s\n", err)
}
idleTimeout = t
}
client := redis.NewClient(&redis.Options{
Addr: config.Addr,
Password: config.Password,
DB: config.DB,
PoolSize: config.PoolSize,
MinIdleConns: config.MinIdleConn,
MaxConnAge: maxConnAge,
IdleTimeout: idleTimeout,
})
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
rd := &MyRedis{}
rd.Client = client
ping := rd.Client.Ping(ctx)
if ping.Err() != nil {
return nil, fmt.Errorf("connet redis err: %s", ping.Err())
}
return rd, nil
}
// GetSimple 通用get
func (r *MyRedis) GetSimple(key string) (string, error) {
ctx := context.Background()
return r.Client.Get(ctx, key).Result()
}
// SetSimple 通用set
func (r *MyRedis) SetSimple(key string, value interface{}, t ...time.Duration) (string, error) {
ctx := context.Background()
var t2 time.Duration
if len(t) > 0 {
t2 = t[0]
}
return r.Client.Set(ctx, key, value, t2).Result()
}
// GetJson json序列化
func (r *MyRedis) GetJson(key string, result interface{}) error {
ctx := context.Background()
res, err := r.Client.Get(ctx, key).Bytes()
if err != nil {
return err
}
err = jsoniter.Unmarshal(res, &result)
if err != nil {
return fmt.Errorf("get key:%s 反序列化json失败(-2)", key)
}
return nil
}
// SetJson json序列化set
func (r *MyRedis) SetJson(key string, value interface{}, t ...time.Duration) (string, error) {
ctx := context.Background()
var t2 time.Duration
if len(t) > 0 {
t2 = t[0]
}
v, err := jsoniter.Marshal(value)
if err != nil {
return "", fmt.Errorf("set key:%s 序列化json失败", key)
}
return r.Client.Set(ctx, key, v, t2).Result()
}
func CloseInstance(key string) {
Instance(key).Client.Close()
}
func CloseAllInstance() {
for _, v := range instanceMap {
v.Client.Close()
}
}