39 lines
731 B
Go
39 lines
731 B
Go
package redisx
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type Client struct {
|
|
rdb *redis.Client
|
|
}
|
|
|
|
func Open(addr string) (*Client, error) {
|
|
if addr == "" {
|
|
return &Client{}, nil
|
|
}
|
|
rdb := redis.NewClient(&redis.Options{Addr: addr})
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*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 }
|