首页 > 解决方案 > 连接(本地主机:27017 [-4])未能写入:上下文已取消

问题描述

在这里我读到有必要取消上下文。这就是我的db.go样子:

package db

import (
    "context"
    "fmt"
    "log"
    "os"
    "time"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

const (
    connectionStringTemplate = "mongodb://%s:%s@%s"
)

var DB *mongo.Client
var Ctx context.Context

// Connect with create the connection to MongoDB
func Connect() {
    username := os.Getenv("MONGODB_USERNAME")
    password := os.Getenv("MONGODB_PASSWORD")
    clusterEndpoint := os.Getenv("MONGODB_ENDPOINT")

    connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint)

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI))
    if err != nil {
        log.Printf("Failed to create client: %v", err)
    }

    err = client.Connect(ctx)
    if err != nil {
        log.Printf("Failed to connect to cluster: %v", err)
    }

    // Force a connection to verify our connection string
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Printf("Failed to ping cluster: %v", err)
    }

    DB = client
    Ctx = ctx
    log.Printf("Connected to MongoDB!")
}

我在以下执行此操作main.go

func main() {

    // Configure
    db.Connect()
    defer db.DB.Disconnect(context.Background())

    r := gin.Default()

    // Routes
    //r.GET("/movies", handlers.GetAllMoviesHandler)
    r.POST("/movies", handlers.AddMovieHandler)

    // listen and serve on 0.0.0.0:8080
    r.Run()
}

如果我的本地 mongodb 正在运行,它工作正常。现在当我像这样使用客户端时(我知道命名仍然不好):

func AddMovie(movie *Movie) (primitive.ObjectID, error) {
    movie.ID = primitive.NewObjectID()
    result, err := db.DB.Database("movies").Collection("movies").InsertOne(db.Ctx, movie)
    if err != nil {
        log.Printf("Could not create movie: %v", err)
        return primitive.NilObjectID, err
    }
    oid := result.InsertedID.(primitive.ObjectID)
    return oid, nil
}

我收到这样的错误

{"msg":{"Code":0,"Message":"connection(localhost:27017[-4]) failed to write: context canceled","Labels":["NetworkError","RetryableWriteError"],"Name":"","Wrapped":{"ConnectionID":"localhost:27017[-4]","Wrapped":{}}}}

当我发表评论时它工作正常,defer cancel()但我想这不正确?我在这里做错了什么。

更新:

它在我使用时有效: result, err :=db.DB.Database("movies").Collection("movies").InsertOne(context.Background(), movie)而不是 ctx. 我不完全理解这些用例中上下文的用法。我也不确定是否应该Ctx = ctx在 Connect 函数中执行。

标签: mongodbgo

解决方案


推荐阅读