package redis import ( "context" "datart/config" "time" "github.com/redis/go-redis/v9" ) var client *redis.Client func init() { config := config.Conf().RedisConf("default") client = redis.NewClient(&redis.Options{ Addr: config.Addr, Username: config.Username, Password: config.Password, DB: config.DB, Protocol: config.Protocol, 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 func Close() 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() } func Keys(ctx context.Context, pattern string) ([]string, error) { batch := int64(1000) cursor := uint64(0) keys := make([]string, 0) for { ks, nextCursor, err := client.Scan(ctx, cursor, pattern, batch).Result() if err != nil { return nil, err } keys = append(keys, ks...) cursor = nextCursor if cursor == 0 { break } } return keys, nil }