Suscríbete a un tema de Pub/Sub
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Demuestra cómo suscribirse a un tema y analizar el evento recibido con Pub/Sub desde Cloud Functions.
Muestra de código
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page demonstrates how to subscribe to a topic using Pub/Sub from Cloud Functions.\u003c/p\u003e\n"],["\u003cp\u003eThe content provides code samples in Java, Node.js, and Python, illustrating how to parse received events.\u003c/p\u003e\n"],["\u003cp\u003eIt highlights the necessity of setting up Application Default Credentials for authenticating to Cloud Run functions.\u003c/p\u003e\n"],["\u003cp\u003eIt shows that the code will print out the data that comes in from the Pub/Sub.\u003c/p\u003e\n"]]],[],null,["# Pub/Sub Subscribe to a Topic\n\nDemonstrates how to subscribe to a topic and parse the received event with Pub/Sub from Cloud Functions.\n\nCode sample\n-----------\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.functions.BackgroundFunction;\n import com.google.cloud.functions.Context;\n import functions.eventpojos.PubsubMessage;\n import java.nio.charset.StandardCharsets;\n import java.util.Base64;\n import java.util.logging.Logger;\n\n public class SubscribeToTopic implements BackgroundFunction\u003cPubsubMessage\u003e {\n private static final Logger logger = Logger.getLogger(SubscribeToTopic.class.getName());\n\n @Override\n public void accept(PubsubMessage message, Context context) {\n if (message.getData() == null) {\n logger.info(\"No message provided\");\n return;\n }\n\n String messageString = new String(\n Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),\n StandardCharsets.UTF_8);\n logger.info(messageString);\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n /**\n * Triggered from a message on a Cloud Pub/Sub topic.\n *\n * @param {object} pubsubMessage The Cloud Pub/Sub Message object.\n * @param {string} pubsubMessage.data The \"data\" property of the Cloud Pub/Sub Message.\n */\n exports.subscribe = pubsubMessage =\u003e {\n // Print out the data from Pub/Sub, to prove that it worked\n console.log(Buffer.from(pubsubMessage.data, 'base64').toString());\n };\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n # Triggered from a message on a Cloud Pub/Sub topic.\n def subscribe(event, context):\n # Print out the data from Pub/Sub, to prove that it worked\n print(base64.b64decode(event[\"data\"]))\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]