spark-server/internal/infrastructure/redis/redis.go
zhr ae9a71034d feat: implement Spark IM V3 modular monolith
Add HTTP /v1 MVC, TCP send path, groups with server-side member-avatar collage, object-storage upload, and friends/favorites around the architecture-v3 layout.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 19:52:11 +08:00

62 lines
1.2 KiB
Go

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()
}