【问题标题】:Golang reports "context deadline exceeded" with MongoDBGolang 报告 MongoDB “超出上下文截止日期”
【发布时间】:2019-07-02 09:14:59
【问题描述】:

我写了一个更新函数,但是多次执行会报错context deadline exceeded

我的功能:

func Update(link string, m bson.M) {
    configInfo := config.Config()

    // client := GetInstance().client
    // ctx := GetInstance().ctx

    client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    err := client.Connect(ctx)
    if err != nil {
        fmt.Print("connect error!")
        fmt.Println(err)
    }
    db := client.Database("test")
    lianjia := db.Collection("test")
    _, err = lianjia.UpdateOne(ctx, bson.M{"Link": link}, bson.M{"$set": m})
    if err != nil {
        fmt.Print("update error!")
        fmt.Println(err)
    }
}

输出:

update error!context deadline exceeded

【问题讨论】:

  • 首先:检查所有您的错误 (mongo.NewClient())。下一个:mongo.Connect() 不会阻止服务器发现。即使您无法连接,它也可能无错误地返回。使用Client.Ping() 验证客户端可以连接到拓扑。
  • @icza Client.ping() 输出“客户端断开连接”,为什么断开连接?
  • 您可能根本无法连接。可能有几个原因,例如错误的 URI,没有运行 MongoDB 服务器等...
  • @icza 但是我已经更新了一些数据。我通过docker用官方镜像构建了MongoDB。
  • 你用的是哪个mongodb版本 Go mongo驱动不支持Mongo 2.4 jira.mongodb.org/browse/GODRIVER-1571

标签: mongodb go


【解决方案1】:

更改 mongodb://localhost:27017 改为 mongodb://127.0.0.1:27017/

【讨论】:

    【解决方案2】:

    尝试使用

    ctx := context.Background()
    

    而不是,

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

    当我尝试使用 MongoDB 服务器开发 REST 后端时,这解决了我的问题

    【讨论】:

      【解决方案3】:

      您的 URI 错误,因为您使用的是 docker。

      如果您的 mongoDB 容器名为 mongoContainer, 你应该:

      client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://mongoContainer"))
      

      【讨论】:

      • 需要更多解释为什么这不起作用。使用docker使用有什么区别
      【解决方案4】:

      在 GoLand 中调试时有时会发生这种情况,如果您有断点并且程序等待然后您继续并收到此错误。如果您删除断点并再次运行程序,它就可以工作。至少我的情况是这样。

      【讨论】:

        【解决方案5】:

        尝试更改您的上下文超时时间,例如 30 秒

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-12-08
          • 1970-01-01
          • 2022-07-11
          • 1970-01-01
          • 2022-08-04
          • 1970-01-01
          • 2018-09-23
          相关资源
          最近更新 更多