Raccolta memorizzata nella cache
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Funzione Cloud Functions HTTP che utilizza un'istanza della libreria client memorizzata nella cache per ridurre il numero di connessioni richieste per ogni chiamata di funzione.
Per saperne di più
Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:
Esempio di codice
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis content demonstrates an HTTP Cloud Function that utilizes a cached client library instance to minimize connection requirements per function call.\u003c/p\u003e\n"],["\u003cp\u003eThe provided Node.js and Python code samples show how to set up and use a cached client to publish messages to a Cloud Pub/Sub topic.\u003c/p\u003e\n"],["\u003cp\u003eProper authentication for Cloud Run functions requires setting up Application Default Credentials, as detailed in the linked documentation.\u003c/p\u003e\n"],["\u003cp\u003eThe Python code provided also makes use of the environment variable \u003ccode\u003eGCP_PROJECT\u003c/code\u003e, which is set automatically in older runtimes, but must be specified in newer runtimes.\u003c/p\u003e\n"]]],[],null,["# Cached library\n\nHTTP Cloud Function that uses a cached client library instance to reduce the number of connections required per function invocation.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Optimize networking (1st gen)](/functions/1stgendocs/bestpractices/networking)\n\nCode sample\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 const functions = require('@google-cloud/functions-framework');\n const {PubSub} = require('https://cloud.google.com/nodejs/docs/reference/pubsub/latest/overview.html');\n const pubsub = new https://cloud.google.com/nodejs/docs/reference/pubsub/latest/pubsub/pubsub.html();\n\n /**\n * HTTP Cloud Function that uses a cached client library instance to\n * reduce the number of connections required per function invocation.\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} req.body Cloud Function request context body.\n * @param {String} req.body.topic The Cloud Pub/Sub topic to publish to.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('gcpApiCall', (req, res) =\u003e {\n const topic = pubsub.topic(req.body.topic);\n\n const data = Buffer.from('Test message');\n topic.publishMessage({data}, err =\u003e {\n if (err) {\n res.status(500).send(`Error publishing the message: ${err}`);\n } else {\n res.status(200).send('1 message published');\n }\n });\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 import os\n\n import functions_framework\n from google.cloud import pubsub_v1\n\n\n # Create a global Pub/Sub client to avoid unneeded network activity\n pubsub = pubsub_v1.https://cloud.google.com/python/docs/reference/pubsublite/latest/google.cloud.pubsublite.cloudpubsub.publisher_client.PublisherClient.html()\n\n\n @functions_framework.http\n def gcp_api_call(request):\n \"\"\"\n HTTP Cloud Function that uses a cached client library instance to\n reduce the number of connections required per function invocation.\n Args:\n request (flask.Request): The request object.\n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response\u003e.\n \"\"\"\n\n \"\"\"\n The `GCP_PROJECT` environment variable is set automatically in the Python 3.7 runtime.\n In later runtimes, it must be specified by the user upon function deployment.\n See this page for more information:\n https://cloud.google.com/functions/docs/configuring/env-var#python_37_and_go_111\n \"\"\"\n project = os.getenv(\"GCP_PROJECT\")\n request_json = request.get_json()\n\n topic_name = request_json[\"topic\"]\n topic_path = pubsub.topic_path(project, topic_name)\n\n # Process the request\n data = b\"Test message\"\n pubsub.https://cloud.google.com/python/docs/reference/pubsublite/latest/google.cloud.pubsublite.cloudpubsub.publisher_client.PublisherClient.html(topic_path, data=data)\n\n return \"1 message published\"\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)."]]