package cache import ( "context" "fmt" "WchimeGinSystem/conf" "log" "time" "github.com/go-redis/redis/v8" ) var CTX = context.Background() var RDB *redis.Client func connectRedis() { rdb_addr := fmt.Sprintf("%s:%s", conf.REDIS_HOST, conf.REDIS_PORT) RDB = redis.NewClient(&redis.Options{ Addr: rdb_addr, Password: conf.REDIS_PWD, DB: conf.REDIS_LIBRARY, }) if err := RDB.Ping(CTX).Err(); err != nil { log.Fatalf("Redis连接失败:%s", err) } } func reconnect() { for { time.Sleep(5 * time.Second) // 每5秒尝试重连 log.Println("尝试重连Redis...") rdb_addr := fmt.Sprintf("%s:%s", conf.REDIS_HOST, conf.REDIS_PORT) RDB = redis.NewClient(&redis.Options{ Addr: rdb_addr, Password: conf.REDIS_PWD, DB: conf.REDIS_LIBRARY, }) if err := RDB.Ping(CTX).Err(); err == nil { log.Println("Redis连接成功.") return } } } func InitRedis() { fmt.Println("开始连接Redis...") connectRedis() go func() { for { time.Sleep(5 * time.Second) // 每5秒检测一次连接 if err := RDB.Ping(CTX).Err(); err != nil { log.Println("Redis丢失连接,尝试重新连接...") reconnect() } } }() }
完整代码地址:https://gitee.com/mom925/gin-system
标签:err,redis,REDIS,conf,RDB,Gin,Redis,链接 From: https://www.cnblogs.com/moon3496694/p/18549130