package service import ( "context" "fmt" "time" "github.com/redis/go-redis/v9" "wx_service/config" ) type Client struct { rc *redis.Client keyPrefix string sessionTTL time.Duration } func NewClient(cfg config.RedisConfig) (*Client, error) { if cfg.Addr == "" { return nil, nil } rc := redis.NewClient(&redis.Options{ Addr: cfg.Addr, Password: cfg.Password, DB: cfg.DB, }) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := rc.Ping(ctx).Err(); err != nil { return nil, fmt.Errorf("ping redis: %w", err) } ttlSeconds := cfg.SessionTTLSeconds if ttlSeconds <= 0 { ttlSeconds = 86400 } return &Client{ rc: rc, keyPrefix: cfg.KeyPrefix, sessionTTL: time.Duration(ttlSeconds) * time.Second, }, nil } func (c *Client) Redis() *redis.Client { return c.rc } func (c *Client) KeyPrefix() string { return c.keyPrefix } func (c *Client) SessionTTL() time.Duration { return c.sessionTTL }