Bibliothèque en cache
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Découvrez une fonction Cloud HTTP qui utilise une instance de bibliothèque cliente en cache pour réduire le nombre de connexions requises par appel de fonction.
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","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)."]]