package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"time"
)
var MongoClient *mongo.Database
func main() {
mongoInit()
}
// pool 连接池模式
func mongoInit() {
user := "score"
password := "HnTcPKsZW8rp4o6O"
host := "s-2ze4f91385c96964-pub.mongodb.rds.aliyuncs.com"
port := "3717"
dbName := "score"
timeOut := 2
maxNum := 100
host1 := "s-2ze5dab972ad1714-pub.mongodb.rds.aliyuncs.com"
uri := fmt.Sprintf("mongodb://%s:%s,%s:%s", host, port, host1, port)
// 设置连接超时时间
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeOut)*time.Second)
defer cancel()
// 通过传进来的uri连接相关的配置
credential := options.Credential{
//AuthMechanism: "SCRAM-SHA-256",
Username: user,
Password: password,
AuthSource: "score",
}
o := options.Client().ApplyURI(uri).SetAuth(credential)
// 设置最大连接数 - 默认是100 ,不设置就是最大 max 64
o.SetMaxPoolSize(uint64(maxNum))
// 发起链接
client, err := mongo.Connect(ctx, o)
if err != nil {
fmt.Println("ConnectToMongoDB", err)
return
}
// 判断服务是不是可用
ctx2, cancel2 := context.WithTimeout(context.Background(), time.Duration(timeOut)*time.Second)
defer cancel2()
if err = client.Ping(ctx2, readpref.Primary()); err != nil {
fmt.Println("ConnectToMongoDB1", err)
return
}
// 返回 client
MongoClient = client.Database(dbName)
}