Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Gatilhos do Pub/Sub (1ª geração)
No Cloud Run functions, um acionador Pub/Sub permite que uma função seja chamada
em resposta a mensagens do Pub/Sub. Ao especificar um acionador do Pub/Sub para uma função, você também especifica um tópico do Pub/Sub. A função será chamada sempre que uma mensagem for publicada no
tópico especificado.
Para que uma função use um acionador Pub/Sub, ela precisa ser implementada como uma
função orientada a eventos:
Se você usar uma
função em segundo plano,
o payload de dados de eventos do Pub/Sub será transmitido diretamente para sua função
no formato
PubsubMessage.
O repositório
Eventos do Google
contém outros recursos para trabalhar com dados de eventos.
Implantação
É possível especificar um acionador Pub/Sub ao implantar uma função. Consulte
Implantar uma função do Cloud para
instruções gerais sobre como implantar uma função. Veja abaixo
mais informações específicas para configurar acionadores do Pub/Sub durante
a implantação.
gcloud
Se você estiver implantando usando a CLI gcloud, as sinalizações mostradas abaixo serão usadas para configurar acionadores do Pub/Sub:
A sinalização
--trigger-topic
especifica o tópico do Pub/Sub que o gatilho vai monitorar.
As mensagens publicadas neste tópico acionarão chamadas para sua função.
Esse tipo de evento é compatível com funções legadas que já consomem
esses eventos. No entanto, recomendamos o uso da sinalização --trigger-topic, porque
o tipo de evento legado pode ser removido em uma data futura.
No campo Selecione um tópico do Cloud Pub/Sub, escolha um tópico para o
acionador monitorar ou selecione Criar um tópico para abrir uma janela para
crie um novo tópico. Quando uma mensagem é publicada no tópico da sua função, isso aciona uma chamada para a função.
Marque ou limpe a caixa de seleção Tentar novamente em caso de falha para controlar
se as chamadas de função com falha são repetidas automaticamente. Consulte
Como repetir funções orientadas a eventos
para mais informações.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-01-31 UTC."],[[["\u003cp\u003ePub/Sub triggers in Cloud Run functions (1st gen) allow functions to be invoked in response to Pub/Sub messages published to a specified topic.\u003c/p\u003e\n"],["\u003cp\u003eFunctions using Pub/Sub triggers must be implemented as event-driven functions, either CloudEvent functions or background functions, and handle data in the appropriate format.\u003c/p\u003e\n"],["\u003cp\u003eDeployment of functions with Pub/Sub triggers can be configured using either the gcloud CLI with the \u003ccode\u003e--trigger-topic\u003c/code\u003e flag or the Google Cloud console by selecting the Cloud Pub/Sub trigger type.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003e--retry\u003c/code\u003e flag in the gcloud CLI or the "Retry on failure" checkbox in the console controls whether failed function calls triggered by Pub/Sub events are automatically retried.\u003c/p\u003e\n"],["\u003cp\u003eLegacy functions can use a different event type specified by \u003ccode\u003eproviders/cloud.pubsub/eventTypes/topic.publish\u003c/code\u003e, however it is recommended to use \u003ccode\u003e--trigger-topic\u003c/code\u003e as this method might be removed in the future.\u003c/p\u003e\n"]]],[],null,["# Pub/Sub triggers (1st gen)\n==========================\n\nIn Cloud Run functions, a Pub/Sub trigger enables a function to be called\nin response to [Pub/Sub](/pubsub/docs) messages. When you specify a\nPub/Sub trigger for a function, you also specify a Pub/Sub\ntopic. Your function will be called whenever a message is published to the\nspecified topic.\n\nFor a function to use a Pub/Sub trigger, it must be implemented as an\n[event-driven function](/functions/1stgendocs/writing/write-event-driven-functions):\n\n- If you use a\n [CloudEvent function](/functions/1stgendocs/writing/write-event-driven-functions#cloudevent-functions),\n the Pub/Sub event data is passed to your function in the\n [CloudEvents format](/eventarc/docs/cloudevents) and the CloudEvent data\n payload is of type\n [`MessagePublishedData`](https://github.com/googleapis/google-cloudevents/blob/main/proto/google/events/cloud/pubsub/v1/data.proto).\n\n- If you use a\n [background function](/functions/1stgendocs/writing/write-event-driven-functions#background-functions),\n the Pub/Sub event data payload is passed directly to your function\n in the\n [`PubsubMessage`](https://github.com/googleapis/google-cloudevents/blob/main/proto/google/events/cloud/pubsub/v1/data.proto)\n format.\n\nThe\n[Google Events](https://github.com/googleapis/google-cloudevents)\nrepository contains additional resources for working with event data.\n\nDeployment\n----------\n\nYou can specify a Pub/Sub trigger when you deploy a function. See\n[Deploy a Cloud Run function](/functions/1stgendocs/deploy) for\ngeneral instructions on how to deploy a function, and see this\nsection for additional information specific to configuring Pub/Sub\ntriggers during deployment. \n\n### gcloud\n\nIf you are\n[deploying using the gcloud CLI](/functions/1stgendocs/deploy#gcloud),\nthe flags shown here are used to configure Pub/Sub triggers: \n\n```sh\ngcloud functions deploy YOUR_FUNCTION_NAME \\\n--no-gen2 \\\n--trigger-topic=YOUR_PUBSUB_TOPIC \\\n[--retry] \\\n...\n```\n\n- The [`--trigger-topic`](/sdk/gcloud/reference/functions/deploy#--trigger-topic) flag specifies the Pub/Sub topic that the trigger will monitor. Messages published to this topic trigger calls to your function.\n- The [`--retry`](/sdk/gcloud/reference/functions/deploy#--retry) flag controls whether failed function calls are automatically retried. See [Retrying event-driven functions](/functions/1stgendocs/bestpractices/retries) for more information.\n\n**Legacy Pub/Sub events**\n\nLegacy functions in Cloud Run functions (1st gen) use a different event type\nfor Pub/Sub triggers: \n\n```sh\ngcloud functions deploy YOUR_FUNCTION_NAME \\\n--no-gen2 \\\n--trigger-event=providers/cloud.pubsub/eventTypes/topic.publish \\\n--trigger-resource=YOUR_PUBSUB_TOPIC \\\n...\n```\n\nThis event type is supported for legacy functions already consuming these\nevents. However, we recommend using the `--trigger-topic` flag instead, as\nthe legacy event type might be removed at a future date.\n\n### Console\n\nIf you are\n[deploying using the Google Cloud console](/functions/1stgendocs/deploy#console),\nyou can configure a Pub/Sub trigger in the **Trigger** section:\n\n1. In the **Trigger type** field, select **Cloud Pub/Sub**.\n2. In the **Select a Cloud Pub/Sub topic** field, select a topic for the trigger to monitor, or select **Create a topic** to open a window to create a new topic. When a message is published to your function's topic, that triggers a call to your function.\n3. Select or clear the **Retry on failure** checkbox to control whether failed function calls are automatically retried. See [Retrying event-driven functions](/functions/1stgendocs/bestpractices/retries) for more information.\n\nNext steps\n----------\n\n- Learn how to [write event-driven functions](/functions/1stgendocs/writing/write-event-driven-functions).\n- Learn how to [deploy a Cloud Run function](/functions/1stgendocs/deploy).\n- See the [Pub/Sub tutorial](/functions/1stgendocs/tutorials/pubsub-1st-gen) for an example of writing, deploying, and calling a function with a Pub/Sub trigger."]]