New
This commit is contained in:
30
internal/store/factory.go
Normal file
30
internal/store/factory.go
Normal file
@@ -0,0 +1,30 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user