添加redis连接
This commit is contained in:
50
init/redisInit/redisInit.go
Normal file
50
init/redisInit/redisInit.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package redisInit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-redis/redis/v8"
|
||||
"gopkg.in/yaml.v3"
|
||||
"os"
|
||||
"time"
|
||||
"toutoukan/model/config"
|
||||
)
|
||||
|
||||
var RedisClient *redis.Client
|
||||
var Ctx = context.Background()
|
||||
|
||||
func RedisInit() error {
|
||||
// 读取配置文件
|
||||
data, err := os.ReadFile("./config.yaml")
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取配置文件失败: %w", err)
|
||||
}
|
||||
|
||||
// 解析配置
|
||||
var cfg config.Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return fmt.Errorf("解析YAML失败: %w", err)
|
||||
}
|
||||
|
||||
// 创建Redis客户端
|
||||
RedisClient = redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%d", cfg.Redis.Host, cfg.Redis.Port), // 地址:端口
|
||||
Password: cfg.Redis.Password, // 密码,无密码则为空
|
||||
// 连接池配置
|
||||
PoolSize: 10, // 连接池大小
|
||||
MinIdleConns: 2, // 最小空闲连接数
|
||||
MaxConnAge: 30 * time.Minute, // 连接最大存活时间
|
||||
IdleTimeout: 5 * time.Minute, // 空闲连接超时时间
|
||||
ReadTimeout: 3 * time.Second, // 读取超时时间
|
||||
WriteTimeout: 3 * time.Second, // 写入超时时间
|
||||
})
|
||||
|
||||
// 测试连接
|
||||
_, err = RedisClient.Ping(Ctx).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Redis连接失败: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Redis连接初始化成功")
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user