[英]Publishing to google pub sub asynchronously through goroutine
我正在尝试通过goroutine异步将消息推送到google pub-sub,但panic: not an App Engine context
以下错误panic: not an App Engine context
我正在使用mux并具有api处理程序
n =一百万
func apihandler(w http.ResponseWriter, r *http.Request) {
go createuniquecodes(n)
return "request running in background"
}
func createuniquecodes(n) {
c := make(chan string)
go createuniquecodes(c, n)
for val := range c {
publishtopubsub(val)
}
}
func createuniquecodes(n) {
for i := 0; i < n; i++ {
uniquecode := some random string
// publish to channel and pubsub
c <- uniquecode
}
close(c)
}
func publishuq(msg string) error {
ctx := context.Background()
client, err := pubsub.NewClient(ctx, projectId)
if err != nil {
log.Fatalf("Could not create pubsub Client: %v", err)
}
t := client.Topic(topicName)
result := t.Publish(ctx, &pubsub.Message{
Data: []byte(msg),
})
id, err := result.Get(ctx)
if err != nil {
return err
}
fmt.Printf("Published a message; msg ID: %v\n", id)
return nil
}
请注意,我需要生成500万个唯一代码,因为我异步执行所有操作,因此我将如何在go例程中定义上下文
我假设您使用的是App Engine标准(非灵活)环境。 请注意,“请求处理程序(在您的情况下为apihandler
)在有限的时间内生成并返回对请求的响应, 通常为60秒左右 。一旦达到期限,请求处理程序将被中断”。
您尝试在调用go createuniquecodes(n)
,然后ctx := context.Background()
时“中断”请求是因为not an App Engine context
了紧急not an App Engine context
。 从技术上讲,您可以使用NewContext(req * http.Request)从原始上下文中获取有效上下文,但是同样,请求超时之前只有60s。
请查看TaskQueues ,因为它们“允许应用程序在用户请求之外异步执行称为任务的工作”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.