[英]Using Cloud Run on a PubSub topic
It was not clear to me how to use Cloud Run on a PubSub topic for for medium-run tasks (inside of the time limit of Cloud Run, of course.) 我不清楚如何在PubSub主题上使用Cloud Run来执行中等运行任务(当然,在Cloud Run的时间限制内)。
Let's see this example taken from the tutorials[1]: 让我们看一下教程[1]中的这个例子:
app.post('/', (req, res) => {
if (!req.body) {
const msg = 'no Pub/Sub message received'
console.error(`error: ${msg}`)
res.status(400).send(`Bad Request: ${msg}`)
return
}
if (!req.body.message) {
const msg = 'invalid Pub/Sub message format'
console.error(`error: ${msg}`)
res.status(400).send(`Bad Request: ${msg}`)
return
}
const pubSubMessage = req.body.message
const name = pubSubMessage.data
? Buffer.from(pubSubMessage.data, 'base64').toString().trim()
: 'World'
console.log(`Hello ${name}!`)
res.status(204).send()
})
My doubt is: Should it return HTTP 204 only after the task finishes, otherwise the task will terminated sudden? 我的疑问是:它是否应该在任务完成后返回HTTP 204,否则任务将突然终止?
1 - https://cloud.google.com/run/docs/tutorials/pubsub 1 - https://cloud.google.com/run/docs/tutorials/pubsub
My doubt is: Should it return HTTP 204 only after the task finishes, otherwise the task will terminated sudden? 我的疑问是:它是否应该在任务完成后返回HTTP 204,否则任务将突然终止?
You do not have a choice. 你没有选择。 If you return before your task/objective finishes, the CPU will be idled to zero and nothing will happen in your Cloud Run instance. 如果在任务/目标完成之前返回,则CPU将被闲置为零,并且您的Cloud Run实例中不会发生任何事情。
In your example, you are just processing a pub/sub message and extracting the name. 在您的示例中,您只是处理发布/订阅消息并提取名称。 If you return before this is finished, no name will be processed. 如果在完成之前返回,则不会处理任何名称。
Cloud Run is designed for an HTTP Request/Response system. Cloud Run专为HTTP请求/响应系统而设计。 This means processing begins when you receive an HTTP Request (GET, POST, PUT, etc.) and ends when your code returns an HTTP Response (or just returns with no response). 这意味着处理在您收到HTTP请求(GET,POST,PUT等)时开始,并在您的代码返回HTTP响应时结束(或者只返回没有响应)。 You might try to create background threads but there is no guarantee that they will execute once your main function returns. 您可能尝试创建后台线程,但无法保证在主函数返回后它们将执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.