50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"datart/config"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
var client *redis.Client
|
|
|
|
func init() {
|
|
config := config.Conf().RedisConf("demo")
|
|
client = redis.NewClient(&redis.Options{
|
|
Addr: config.Addr,
|
|
Username: config.Username,
|
|
Password: config.Password,
|
|
DB: config.DB,
|
|
Protocol: config.RESP,
|
|
DialTimeout: time.Duration(config.GetDialTimeout()) * time.Millisecond,
|
|
ReadTimeout: time.Duration(config.GetReadTimeout()) * time.Millisecond,
|
|
WriteTimeout: time.Duration(config.GetWriteTimeout()) * time.Millisecond,
|
|
PoolSize: config.PoolSize,
|
|
})
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
defer cancel()
|
|
pong, err := client.Ping(ctx).Result()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if pong != "PONG" {
|
|
panic("redis ping failed")
|
|
}
|
|
}
|
|
|
|
// close redis client with tag
|
|
func Close(tag string) error {
|
|
return client.Close()
|
|
}
|
|
|
|
func Lock(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
|
|
return client.SetNX(ctx, key, value, expiration).Err()
|
|
}
|
|
|
|
func Unlock(ctx context.Context, key string) error {
|
|
return client.Del(ctx, key).Err()
|
|
}
|