aboutsummaryrefslogtreecommitdiffstats
path: root/listener/mongo.go
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--listener/mongo.go15
1 files changed, 12 insertions, 3 deletions
diff --git a/listener/mongo.go b/listener/mongo.go
index a51350e..36c471c 100644
--- a/listener/mongo.go
+++ b/listener/mongo.go
@@ -31,18 +31,27 @@ func (mc *mongoClient) init(dbName, colName string) error {
31 31
32func (mc *mongoClient) Connect(dbName, colName string) error { 32func (mc *mongoClient) Connect(dbName, colName string) error {
33 var err error 33 var err error
34 mc.client, err = mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) 34 // 设置连接MongoDB的参数
35 clientOptions := options.Client().ApplyURI("mongodb://" + *mongoURI)
35 36
37 // 创建一个带有超时的上下文
38 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
39 defer cancel() // 确保在函数退出时取消上下文
40
41 // 使用带超时的上下文连接到MongoDB
42 mc.client, err = mongo.Connect(ctx, clientOptions)
36 if err != nil { 43 if err != nil {
37 return err 44 return err
38 } 45 }
39 46
40 ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) 47 // 尝试ping数据库以检查连接是否成功
41 err = mc.client.Connect(ctx) 48 err = mc.client.Ping(ctx, nil)
42 if err != nil { 49 if err != nil {
43 return err 50 return err
44 } 51 }
45 52
53 fmt.Println("Connected to MongoDB!")
54
46 mc.col = mc.client.Database(dbName).Collection(colName) 55 mc.col = mc.client.Database(dbName).Collection(colName)
47 mc.dbName = dbName 56 mc.dbName = dbName
48 mc.colName = colName 57 mc.colName = colName