【问题标题】:AppEngine: using a context not associated with a requestAppEngine:使用与请求无关的上下文
【发布时间】:2017-10-01 13:52:59
【问题描述】:

我尝试使用 PubSub 和 AppEngine 部署 API,但出现“不是 App Engine 上下文”错误,它与以下代码有关:

import (
    "golang.org/x/net/context"
    "log"

    "cloud.google.com/go/pubsub"
)

var (
    ctx                             context.Context
    pubsubClient                    *pubsub.Client
)  

func InitPubSub () {
    ctx = context.Background()

    psClient, err := pubsub.NewClient(ctx, "myproject-1234")
    if err != nil {
        log.Println("(init pub sub) error while creating new pubsub client:", err)

    } else {
        pubsubClient = psClient

    }
}

所以我查看了 appengine 包中的 BackgroundContext 函数,但它说它只适用于 AppEngine 灵活环境(标准环境似乎更适合我的应用程序): https://godoc.org/google.golang.org/appengine#BackgroundContext

您知道我是否可以使用其他功能吗?还是应该为每个请求创建并关闭一个客户端?

谢谢!

【问题讨论】:

    标签: google-app-engine go google-cloud-platform


    【解决方案1】:

    每个请求都应创建一个新客户端(当客户端需要context 时)。请求的context 处理诸如取消和超时之类的事情。因此,如果您的请求被取消,您还应该取消任何传出的 API 请求。客户端处理所有传出的 API 请求,因此它需要相同的 context

    App Engine 标准要求使用 App Engine 上下文的请求,因为它会自动处理缩放和资源。

    您可以通过调用appengine.NewContext(req) (g3doc) 从请求中获取context.Context

    例如:

    import (
            "net/http"
    
            "cloud.google.com/go/pubsub"
            "google.golang.org/appengine"
            "google.golang.org/appengine/log"
    )
    
    func pubSubHandler(w http.ResponseWriter, r *http.Request) {
        ctx := appengine.NewContext(r)
        client, err := pubsub.NewClient(ctx, "myproject-1234")
        if err != nil {
            log.Errorf(ctx, "pubsub.NewClient: %v", err)
            http.Error(w, "An error occurred. Try again.", http.StatusInternalServerError)
            return
        }
        _ = client // Use the client.
    }
    

    另一个注意事项是使用google.golang.org/appengine/log 包在App Engine Standard 中进行登录,如上所述。见Reading and Writing Application Logs

    来自官方文档的Building an App with Go 描述了如何在 App Engine Standard 上构建示例应用程序。

    【讨论】:

      猜你喜欢
      • 2011-12-27
      • 2021-06-20
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 2014-04-26
      相关资源
      最近更新 更多