登录
首页 >  Golang >  Go问答

Golang cli 应用程序 - 如何正确使用上下文?

来源:stackoverflow

时间:2024-04-02 08:54:35 162浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Golang cli 应用程序 - 如何正确使用上下文?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我是 golang 新手,对上下文以及如何在 golang 应用程序中使用上下文有些困惑。 具体来说,我正在开发 cli 应用程序,只需要访问 mongo,例如。

就像 - 我只是创建单个共享 ctx 上下文变量,然后将其用于任何需要上下文的操作,这是正确的吗?

任何需要上下文的操作都会重新启动 5 秒计时器吗?或者这是一个共享计时器?

package main

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

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

func main() {

    log.SetOutput(os.Stdout)

    // Create a context with a timeout of 5 seconds
    //This defines a timeout context that will be canceled after 5 seconds.
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    // always defer in case func returns early
    defer cancel()

    //Creates a new ClientOptions instance.
    clientOptions := options.Client()
    clientOptions = clientOptions.ApplyURI("mongodb+srv://127.0.0.1?retryWrites=true&w=majority")

    //Connect to mongo
    client, err := mongo.Connect(ctx, clientOptions)
    defer client.Disconnect(ctx)
    if err != nil {
        log.Fatal(err)
    }

    //Test connection to the database
    log.Println("I: test mongo connection using ping")
    err = client.Ping(ctx, readpref.Primary())
    if err != nil {
        log.Fatal(err)
    }

    log.Println("I: Fin")
}

正确答案


如果你仔细想想,context.context 可以“水平”共享(意思是在不属于同一调用堆栈的操作之间)是没有意义的。 golang context 提供了要执行操作(包括调用堆栈中其下方的任何嵌套操作)的上下文 - 例如“在 x 秒内”,以防止由于通信延迟等而挂起。因此,如果您发出并行 10 个请求,您应该为每个请求提供自己的上下文 - 您可能不希望第十个请求失败,因为第一个请求失败了。如果您只是使用 context.background()context.todo(),没有进一步的装饰,您可能不需要在第一次创建它时将 context 存储在变量中 - 您可以在创建时创建将其传递给调用堆栈中的第一个函数,正确构造的代码将根据需要将其向下传递到堆栈,并一路应用必要的修饰:

func Execute() {
  DoThing(context.Background())
  // Other stuff
}

func DoThing(pctx context.Context) {
  ctx, cancel := context.WithTimeout(pctx, 10 * time.Second) // Timeout after 10 seconds
  defer cancel()

  DoThingThatMayTakeAWhile(ctx)
  select {
    // You may want other stuff here
    case <-ctx.Done():
      // Context timed out, maybe log an error?
  }
}

func DoThingThatMayTakeAWhile(pctx context.Context) {
  DoThingNeedingInfoInContext(context.WithValue(pctx, "thisisakey", "value"))
}

func DoThingNeedingInfoInContext(ctx context.Context) {
  val := ctx.Value("thisisakey")
  // Do something with val, check that it isn't nil, etc.
}
  

如果我要多次调用 dothingthatmaytakeawhile(),我想为每个调用提供一个单独的子上下文 - 我希望与每个调用共享 ctx。 p>

因此,在您的代码中,每次调用 mongo.connect() 都应该收到一个新创建的 context.context 实例。

本篇关于《Golang cli 应用程序 - 如何正确使用上下文?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>