Golang中如何从其他函数调用MongoDB连接?

Golang中如何从其他函数调用MongoDB连接? 我想在Go语言中从另一个函数使用MongoDB连接,示例:

func Conn(){
client, err := 
mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
 }

调用该函数。

func main(){
    Conn.client()//类似这样
}
4 回复

我是这样解决的

var CNX = Connection()
func Connection() *mongo.Client {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
          	log.Fatal(err)
    }

    // Check the connection
    err = client.Ping(context.TODO(), nil)

    if err != nil {
	    log.Fatal(err)
    }

    fmt.Println("Connected to MongoDB!")

    return client
}

//calll connection
 func main() {
      collection := db.CNX.Database("tasks").Collection("task")
 }

output "Connected to MongoDB!"

更多关于Golang中如何从其他函数调用MongoDB连接?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这和下面这段代码不一样吗?

    var CNX = Connection()
    func Connection() *mongo.Client {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
      	log.Fatal(err)
   }

    // Check the connection
    err = client.Ping(context.TODO(), nil)

    if err != nil {
	    log.Fatal(err)
    }

    fmt.Println("Connected to MongoDB!")

    return client
}

//calll connection
 func main() {
      collection := db.CNX.Database("tasks").Collection("task")
 }

这是一种实现方式。另一种方式是使用结构体作为依赖注入工具。

示例:

type AppConnection struct {
  Client *mongo.Client
  IsConnected bool
  // 以及其他你需要的东西,比如模式等
}

func (ac AppConnection) Connect() {
    // 设置客户端选项
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // 连接到 MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
        ac.IsConnected = false
        return
    }

    // 检查连接
    err = client.Ping(context.TODO(), nil)

    if err != nil {
	    ac.IsConnected = false
        return
    }
    
    ac.IsConnected = true
    ac.Client = client

    fmt.Println("Connected to MongoDB!")
}

这样做的好处是,你可以在代码的其他模块中传递 AppConnection 结构体的指针,而无需担心导入时的循环依赖问题。

在Go中从其他函数调用MongoDB连接,通常需要将连接对象作为返回值或存储在包级变量中。以下是几种实现方式:

1. 返回连接对象

package main

import (
    "context"
    "fmt"
    "time"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func Conn() (*mongo.Client, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    
    client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        return nil, err
    }
    
    return client, nil
}

func main() {
    client, err := Conn()
    if err != nil {
        panic(err)
    }
    defer func() {
        if err = client.Disconnect(context.Background()); err != nil {
            panic(err)
        }
    }()
    
    // 使用连接
    collection := client.Database("testdb").Collection("testcollection")
    fmt.Println("Connected to MongoDB")
}

2. 使用包级变量

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

var (
    mongoClient *mongo.Client
    mongoOnce   sync.Once
    mongoErr    error
)

func GetMongoClient() (*mongo.Client, error) {
    mongoOnce.Do(func() {
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        defer cancel()
        
        mongoClient, mongoErr = mongo.Connect(ctx, 
            options.Client().ApplyURI("mongodb://localhost:27017"))
    })
    
    return mongoClient, mongoErr
}

func main() {
    client, err := GetMongoClient()
    if err != nil {
        panic(err)
    }
    
    // 在其他函数中使用
    collection := client.Database("testdb").Collection("users")
    fmt.Println("MongoDB connection ready")
}

3. 使用结构体封装

package main

import (
    "context"
    "fmt"
    "time"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type MongoDB struct {
    Client *mongo.Client
}

func NewMongoDB(uri string) (*MongoDB, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    
    client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
    if err != nil {
        return nil, err
    }
    
    return &MongoDB{Client: client}, nil
}

func (m *MongoDB) Close() error {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    return m.Client.Disconnect(ctx)
}

func (m *MongoDB) GetCollection(dbName, collName string) *mongo.Collection {
    return m.Client.Database(dbName).Collection(collName)
}

func main() {
    mongoDB, err := NewMongoDB("mongodb://localhost:27017")
    if err != nil {
        panic(err)
    }
    defer mongoDB.Close()
    
    // 在多个函数中使用
    usersCollection := mongoDB.GetCollection("testdb", "users")
    ordersCollection := mongoDB.GetCollection("testdb", "orders")
    
    fmt.Printf("Users collection: %v\n", usersCollection.Name())
    fmt.Printf("Orders collection: %v\n", ordersCollection.Name())
}

4. 使用依赖注入

package main

import (
    "context"
    "fmt"
    "time"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func createMongoClient() (*mongo.Client, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    
    return mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
}

func processData(client *mongo.Client) {
    collection := client.Database("testdb").Collection("data")
    fmt.Printf("Processing data with collection: %s\n", collection.Name())
}

func insertRecord(client *mongo.Client, data interface{}) error {
    collection := client.Database("testdb").Collection("records")
    _, err := collection.InsertOne(context.Background(), data)
    return err
}

func main() {
    client, err := createMongoClient()
    if err != nil {
        panic(err)
    }
    defer client.Disconnect(context.Background())
    
    // 将连接传递给其他函数
    processData(client)
    
    record := map[string]interface{}{"name": "John", "age": 30}
    if err := insertRecord(client, record); err != nil {
        fmt.Printf("Insert error: %v\n", err)
    }
}

第一种方式最简单直接,第二种方式实现了单例模式,第三种方式提供了更好的封装,第四种方式适合依赖注入场景。根据应用复杂度选择合适的方式。

回到顶部