Files
gemini-banlancer/internal/store/factory.go
2025-11-20 12:24:05 +08:00

31 lines
1.0 KiB
Go

package store
import (
"context"
"fmt"
"gemini-balancer/internal/config"
"github.com/redis/go-redis/v9"
"github.com/sirupsen/logrus"
)
// NewStore creates a new store based on the application configuration.
func NewStore(cfg *config.Config, logger *logrus.Logger) (Store, error) {
// 检查是否有Redis配置
if cfg.Redis.DSN != "" {
opts, err := redis.ParseURL(cfg.Redis.DSN)
if err != nil {
return nil, fmt.Errorf("failed to parse redis DSN: %w", err)
}
client := redis.NewClient(opts)
if err := client.Ping(context.Background()).Err(); err != nil {
logger.WithError(err).Warnf("WARN: Failed to connect to Redis (%s), falling back to in-memory store. Error: %v", cfg.Redis.DSN, err)
return NewMemoryStore(logger), nil // 连接失败,也回退到内存模式,但不返回错误
}
logger.Info("Successfully connected to Redis. Using Redis as store.")
return NewRedisStore(client), nil
}
logger.Info("INFO: Redis DSN not configured, falling back to in-memory store.")
return NewMemoryStore(logger), nil
}