快取的程式庫
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
HTTP Cloud Function,使用快取用戶端程式庫執行個體,減少每個函式呼叫所需的連線數。
深入探索
如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:
程式碼範例
Node.js
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Python
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","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)."]]