16844d4a42
- Added AI configuration options to .env.example and config.go for OpenAI integration. - Implemented Redis caching for session management in main.go and auth middleware. - Updated smoke logging service to support real smoking time (`smoke_at`) and AI advice retrieval. - Enhanced API routes to include endpoints for AI advice and unlock functionality for non-members. - Improved database schema with new tables for AI advice and unlock records. - Expanded documentation to cover new AI features and Redis caching implementation.
59 lines
1004 B
Go
59 lines
1004 B
Go
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
|
|
}
|