1 Star 0 Fork 0

李小程/blog-lib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
redis.go 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
LiXiaoCheng 提交于 2025-07-19 11:08 +08:00 . init
package database
import (
"context"
"gitee.com/xchengli/blog-lib/config"
"github.com/redis/go-redis/v9"
)
// Redis连接池大小
var MAX_POOL_SIZE = 20
var RedisPoll chan *redis.Client
var RedisConn *redis.Client
func ConnRedis(network, address string) *redis.Client {
// 缓冲机制,相当于消息队列
if len(RedisPoll) == 0 {
// 如果长度为0,就定义一个redis.Conn类型长度为MAX_POOL_SIZE的channel
RedisPoll = make(chan *redis.Client, MAX_POOL_SIZE)
go func() {
for i := 0; i < MAX_POOL_SIZE/2; i++ {
c := redis.NewClient(&redis.Options{
Addr: config.RedisConf.Address,
Password: config.RedisConf.Password,
DB: config.RedisConf.DB,
})
// 测试连接
ctx := context.Background()
_, err := c.Ping(ctx).Result()
if err != nil {
panic(err)
}
putRedis(c)
}
}()
}
return <-RedisPoll
}
func putRedis(conn *redis.Client) {
// 基于函数和接口间互不信任原则,这里再判断一次,养成这个好习惯
if RedisPoll == nil {
RedisPoll = make(chan *redis.Client, MAX_POOL_SIZE)
}
if len(RedisPoll) >= MAX_POOL_SIZE {
conn.Close()
conn = nil
return
}
RedisPoll <- conn
}
func InitRedis() {
if RedisConn == nil {
RedisConn = ConnRedis(config.RedisConf.Network, config.RedisConf.Address)
}
ctx := context.Background()
// 测试连接
_, err := RedisConn.Ping(ctx).Result()
if err != nil {
panic(err)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xchengli/blog-lib.git
git@gitee.com:xchengli/blog-lib.git
xchengli
blog-lib
blog-lib
7bad096cf672

搜索帮助