72 lines
2.0 KiB
Go
72 lines
2.0 KiB
Go
|
|
package config
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"context"
|
|||
|
|
"fmt"
|
|||
|
|
|
|||
|
|
"github.com/redis/go-redis/v9"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// RedisConfig Redis 配置
|
|||
|
|
type RedisConfig struct {
|
|||
|
|
Type string `mapstructure:"type"`
|
|||
|
|
Redis RedisServerConfig `mapstructure:"redis"`
|
|||
|
|
Miniredis MiniredisConfig `mapstructure:"miniredis"`
|
|||
|
|
PoolSize int `mapstructure:"pool_size"`
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// CacheConfig 缓存配置
|
|||
|
|
type CacheConfig struct {
|
|||
|
|
Enabled bool `mapstructure:"enabled"`
|
|||
|
|
KeyPrefix string `mapstructure:"key_prefix"`
|
|||
|
|
DefaultTTL int `mapstructure:"default_ttl"`
|
|||
|
|
NullTTL int `mapstructure:"null_ttl"`
|
|||
|
|
JitterRatio float64 `mapstructure:"jitter_ratio"`
|
|||
|
|
DisableFlushDB bool `mapstructure:"disable_flushdb"`
|
|||
|
|
Modules CacheModuleTTL `mapstructure:"modules"`
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// CacheModuleTTL 缓存模块 TTL 配置
|
|||
|
|
type CacheModuleTTL struct {
|
|||
|
|
PostList int `mapstructure:"post_list_ttl"`
|
|||
|
|
Conversation int `mapstructure:"conversation_ttl"`
|
|||
|
|
UnreadCount int `mapstructure:"unread_count_ttl"`
|
|||
|
|
GroupMembers int `mapstructure:"group_members_ttl"`
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// RedisServerConfig Redis 服务器配置
|
|||
|
|
type RedisServerConfig struct {
|
|||
|
|
Host string `mapstructure:"host"`
|
|||
|
|
Port int `mapstructure:"port"`
|
|||
|
|
Password string `mapstructure:"password"`
|
|||
|
|
DB int `mapstructure:"db"`
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Addr 返回 Redis 服务器地址
|
|||
|
|
func (r RedisServerConfig) Addr() string {
|
|||
|
|
return fmt.Sprintf("%s:%d", r.Host, r.Port)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// MiniredisConfig Miniredis 配置(用于测试)
|
|||
|
|
type MiniredisConfig struct {
|
|||
|
|
Host string `mapstructure:"host"`
|
|||
|
|
Port int `mapstructure:"port"`
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// NewRedis 创建 Redis 客户端(真实 Redis)
|
|||
|
|
func NewRedis(cfg *RedisConfig) (*redis.Client, error) {
|
|||
|
|
client := redis.NewClient(&redis.Options{
|
|||
|
|
Addr: cfg.Redis.Addr(),
|
|||
|
|
Password: cfg.Redis.Password,
|
|||
|
|
DB: cfg.Redis.DB,
|
|||
|
|
PoolSize: cfg.PoolSize,
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
ctx := context.Background()
|
|||
|
|
if err := client.Ping(ctx).Err(); err != nil {
|
|||
|
|
return nil, fmt.Errorf("failed to connect to redis: %w", err)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return client, nil
|
|||
|
|
}
|