Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google app engine AppEngine:使用与请求无关的上下文_Google App Engine_Go_Google Cloud Platform - Fatal编程技术网

Google app engine AppEngine:使用与请求无关的上下文

Google app engine AppEngine:使用与请求无关的上下文,google-app-engine,go,google-cloud-platform,Google App Engine,Go,Google Cloud Platform,我试图使用PubSub和AppEngine部署API,但出现了“非应用程序引擎上下文”错误,它与以下代码有关: import ( "golang.org/x/net/context" "log" "cloud.google.com/go/pubsub" ) var ( ctx context.Context pubsubClient *pubsub.Clien

我试图使用PubSub和AppEngine部署API,但出现了“非应用程序引擎上下文”错误,它与以下代码有关:

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 func,但它说它只适用于appengine灵活的环境(标准环境似乎更适合我的应用程序):

你知道我还能用别的功能吗?还是应该为每个请求创建并关闭一个客户端


谢谢

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

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

通过调用
appengine.NewContext(req)
(),可以从请求中获取
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标准,如上所述。看

从官方文档中介绍了如何在AppEngine标准上构建示例应用程序