Files
2026-08-06 09:49:54 +08:00

59 lines
934 B
Go

package redis
import (
"context"
"fmt"
"time"
goredis "github.com/redis/go-redis/v9"
)
const Nil = goredis.Nil
var Client *goredis.Client
type Config struct {
Host string
Port int
Password string
DB int
}
func Init(c Config) error {
client, err := New(c)
if err != nil {
return err
}
Client = client
return nil
}
func New(c Config) (*goredis.Client, error) {
if c.Host == "" {
return nil, fmt.Errorf("redis: Host is empty")
}
if c.Port == 0 {
c.Port = 6379
}
client := goredis.NewClient(&goredis.Options{
Addr: fmt.Sprintf("%s:%d", c.Host, c.Port),
Password: c.Password,
DB: c.DB,
})
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := client.Ping(ctx).Err(); err != nil {
_ = client.Close()
return nil, fmt.Errorf("redis ping: %w", err)
}
return client, nil
}
func GetRedisKey(key string) string {
return key
}