package redisx import ( "context" "fmt" "time" "github.com/redis/go-redis/v9" ) type Client struct { rdb *redis.Client } // Options configure Open. Empty Addr skips the connection for local bring-up. type Options struct { Addr string Username string Password string DB int } func Open(o *Options) (*Client, error) { if o == nil || o.Addr == "" { return &Client{}, nil } rdb := redis.NewClient(&redis.Options{ Addr: o.Addr, Username: o.Username, Password: o.Password, DB: o.DB, DialTimeout: 10 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, }) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := rdb.Ping(ctx).Err(); err != nil { _ = rdb.Close() return nil, fmt.Errorf("redis ping: %w", err) } return &Client{rdb: rdb}, nil } func (c *Client) RDB() *redis.Client { return c.rdb } func (c *Client) Close() error { if c == nil || c.rdb == nil { return nil } return c.rdb.Close() } func (c *Client) Ready() bool { return c != nil && c.rdb != nil } func (c *Client) Ping(ctx context.Context) error { if !c.Ready() { return nil } return c.rdb.Ping(ctx).Err() }