1 Star 0 Fork 0

玟兵/go-util

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mongodb.go 749 Bytes
一键复制 编辑 原始数据 按行查看 历史
玟兵 提交于 2024-04-30 16:37 +08:00 . 防止缓存击穿
package util
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"runtime"
"time"
)
// NewMongoClient Mongo连接客户端
func NewMongoClient(dsn string) (*mongo.Client, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cpuNum := uint64(runtime.NumCPU())
opt := options.Client().ApplyURI(dsn)
opt.SetMinPoolSize(cpuNum)
opt.SetMaxPoolSize(cpuNum * 4)
return mongo.Connect(ctx, opt)
}
// MongoPing 验证连通性
func MongoPing(client *mongo.Client) error {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
return client.Ping(ctx, readpref.Primary())
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/binny_w/go-util.git
git@gitee.com:binny_w/go-util.git
binny_w
go-util
go-util
v0.0.49

搜索帮助