با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
سادگی Cloud Functions به شما امکان می دهد به سرعت کد را توسعه دهید و آن را در یک محیط بدون سرور اجرا کنید. در مقیاس متوسط، هزینه اجرای توابع کم است و بهینه سازی کد شما ممکن است اولویت بالایی به نظر نرسد. با این حال، همانطور که استقرار شما افزایش می یابد، بهینه سازی کد شما اهمیت فزاینده ای پیدا می کند.
این سند نحوه بهینه سازی شبکه را برای عملکردهای خود شرح می دهد. برخی از مزایای بهینه سازی شبکه به شرح زیر است:
زمان صرف شده برای ایجاد اتصالات خروجی جدید در هر فراخوانی تابع را کاهش دهید.
در این بخش مثال هایی از نحوه حفظ اتصالات پایدار در یک تابع ارائه می شود. عدم انجام این کار می تواند منجر به فرسودگی سریع سهمیه های اتصال شود.
سناریوهای زیر در این بخش پوشش داده شده است:
HTTP/S
API های گوگل
درخواست های HTTP/S
قطعه کد بهینه شده زیر نشان می دهد که چگونه به جای ایجاد یک اتصال جدید در هر فراخوانی تابع، اتصالات پایدار را حفظ کنید:
Node.js
consthttp=require('http');constfunctions=require('firebase-functions');// Setting the `keepAlive` option to `true` keeps// connections open between function invocationsconstagent=newhttp.Agent({keepAlive:true});exports.function=functions.https.onRequest((request,response)=>{req=http.request({host:'',port:80,path:'',method:'GET',agent:agent,// Holds the connection open after the first invocation},res=>{letrawData='';res.setEncoding('utf8');res.on('data',chunk=>{rawData+=chunk;});res.on('end',()=>{response.status(200).send(`Data: ${rawData}`);});});req.on('error',e=>{response.status(500).send(`Error: ${e.message}`);});req.end();});
پایتون
fromfirebase_functionsimporthttps_fnimportrequests# Create a global HTTP session (which provides connection pooling)session=requests.Session()@https_fn.on_request()defconnection_pooling(request):# The URL to send the request tourl="http://example.com"# Process the requestresponse=session.get(url)response.raise_for_status()returnhttps_fn.Response("Success!")
این تابع HTTP از یک مخزن اتصال برای ایجاد درخواست های HTTP استفاده می کند. یک شی درخواست ( flask.Request ) را می گیرد و متن پاسخ یا هر مجموعه ای از مقادیر را که می تواند با استفاده از make_response به یک شی Response تبدیل شود، برمی گرداند.
دسترسی به API های گوگل
مثال زیر از Cloud Pub/Sub استفاده میکند، اما این رویکرد برای سایر کتابخانههای سرویس گیرنده نیز کار میکند - برای مثال، Cloud Natural Language یا Cloud Spanner . توجه داشته باشید که بهبود عملکرد ممکن است به اجرای فعلی کتابخانه های مشتری خاص بستگی داشته باشد.
ایجاد یک شی کلاینت Pub/Sub منجر به یک اتصال و دو درخواست DNS در هر فراخوانی می شود. برای جلوگیری از اتصالات غیر ضروری و پرس و جوهای DNS، شیء مشتری Pub/Sub را در محدوده جهانی همانطور که در نمونه زیر نشان داده شده است ایجاد کنید:
node.js
constPubSub=require('@google-cloud/pubsub');constfunctions=require('firebase-functions');constpubsub=PubSub();exports.function=functions.https.onRequest((req,res)=>{consttopic=pubsub.topic('');topic.publish('Test message',err=>{if(err){res.status(500).send(`Error publishing the message: ${err}`);}else{res.status(200).send('1 message published');}});});
پایتون
importosfromfirebase_functionsimporthttps_fnfromgoogle.cloudimportpubsub_v1# from firebase_functions import https_fn# Create a global Pub/Sub client to avoid unneeded network activitypubsub=pubsub_v1.PublisherClient()@https_fn.on_request()defgcp_api_call(request):project=os.getenv("GCP_PROJECT")request_json=request.get_json()topic_name=request_json["topic"]topic_path=pubsub.topic_path(project,topic_name)# Process the requestdata=b"Test message"pubsub.publish(topic_path,data=data)returnhttps_fn.Response("1 message published")
این تابع HTTP از یک نمونه کتابخانه سرویس گیرنده ذخیره شده برای کاهش تعداد اتصالات مورد نیاز در هر فراخوانی تابع استفاده می کند. یک شی درخواست ( flask.Request ) را می گیرد و متن پاسخ یا هر مجموعه ای از مقادیر را که می تواند با استفاده از make_response به یک شی Response تبدیل شود، برمی گرداند.
متغیر محیطی GCP_PROJECT به طور خودکار در زمان اجرا پایتون 3.7 تنظیم می شود. در زمان اجراهای بعدی، مطمئن شوید که آن را در استقرار تابع مشخص کنید. پیکربندی متغیرهای محیط را ببینید.
اتصالات خروجی
مهلت زمانی درخواست خروجی
پس از 10 دقیقه زمان بیکار برای درخواست های تابع شما به شبکه VPC یک بازه زمانی وجود دارد. برای درخواست از عملکرد شما به اینترنت، پس از 20 دقیقه زمان بیکار، یک بازه زمانی وجود دارد.
اتصال خروجی بازنشانی می شود
جریان های اتصال از عملکرد شما به شبکه VPC و اینترنت می توانند گهگاهی خاتمه یافته و در صورت راه اندازی مجدد یا به روز رسانی زیرساخت های اساسی جایگزین شوند. اگر برنامه شما از اتصالات طولانی مدت استفاده می کند، توصیه می کنیم برنامه خود را طوری پیکربندی کنید که اتصالات را مجدداً برقرار کند تا از استفاده مجدد از اتصال مرده جلوگیری شود.
تست بارگذاری عملکرد شما
برای اندازهگیری تعداد اتصالاتی که تابع شما به طور متوسط انجام میدهد، آن را به عنوان یک تابع HTTP اجرا کنید و از یک چارچوب تست عملکرد برای فراخوانی آن در QPS خاص استفاده کنید. یکی از گزینه های ممکن توپخانه است که می توانید با یک خط از آن استفاده کنید:
$ artillery quick -d 300 -r 30 URL
این دستور URL داده شده را در 30 QPS به مدت 300 ثانیه واکشی می کند.
پس از انجام آزمایش، میزان استفاده از سهمیه اتصال خود را در صفحه سهمیه Cloud Functions API در Cloud Console بررسی کنید. اگر استفاده به طور مداوم حدود 30 (یا چند برابر آن) است، در هر فراخوانی یک (یا چند) اتصال برقرار می کنید. پس از بهینه سازی کد خود، باید مشاهده کنید که چند اتصال (10-30) فقط در ابتدای آزمایش رخ می دهد.
همچنین می توانید هزینه CPU را قبل و بعد از بهینه سازی در نمودار سهمیه CPU در همان صفحه مقایسه کنید.
تاریخ آخرین بهروزرسانی 2025-09-04 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-09-04 بهوقت ساعت هماهنگ جهانی."],[],[],null,["\u003cbr /\u003e\n\nThe simplicity of Cloud Functions lets you quickly develop code and run it in\na serverless environment. At moderate scale, the cost of running functions is\nlow, and optimizing your code might not seem like a high priority. As your\ndeployment scales up, however, optimizing your code becomes increasingly\nimportant.\n\nThis document describes how to optimize networking for your functions. Some of\nthe benefits of optimizing networking are as follows:\n\n- Reduce CPU time spent in establishing new outbound connections at each function call.\n- Reduce the likelihood of running out of connection or DNS [quotas](https://cloud.google.com/functions/quotas).\n\nMaintaining Persistent Connections\n\nThis section gives examples of how to maintain persistent connections in a\nfunction. Failure to do so can result in quickly exhausting connection quotas.\n\nThe following scenarios are covered in this section:\n\n- HTTP/S\n- Google APIs\n\nHTTP/S Requests\n\nThe optimized code snippet below shows how to maintain persistent connections\ninstead of creating a new connection upon every function invocation: \n\nNode.js \n\n```javascript\nconst http = require('http');\nconst functions = require('firebase-functions');\n\n// Setting the `keepAlive` option to `true` keeps\n// connections open between function invocations\nconst agent = new http.Agent({keepAlive: true});\n\nexports.function = functions.https.onRequest((request, response) =\u003e {\n req = http.request({\n host: '',\n port: 80,\n path: '',\n method: 'GET',\n agent: agent, // Holds the connection open after the first invocation\n }, res =\u003e {\n let rawData = '';\n res.setEncoding('utf8');\n res.on('data', chunk =\u003e { rawData += chunk; });\n res.on('end', () =\u003e {\n response.status(200).send(`Data: ${rawData}`);\n });\n });\n req.on('error', e =\u003e {\n response.status(500).send(`Error: ${e.message}`);\n });\n req.end();\n});\n```\n\nPython \n\n```python\nfrom firebase_functions import https_fn\nimport requests\n\n# Create a global HTTP session (which provides connection pooling)\nsession = requests.Session()\n\n@https_fn.on_request()\ndef connection_pooling(request):\n\n # The URL to send the request to\n url = \"http://example.com\"\n\n # Process the request\n response = session.get(url)\n response.raise_for_status()\n return https_fn.Response(\"Success!\")\n \n```\n\nThis HTTP function uses a connection pool to make HTTP requests. It takes a\nrequest object (`flask.Request`) and returns the response text, or any set\nof values that can be turned into a `Response` object using\n[`make_response`](https://flask.palletsprojects.com/en/3.0.x/api/#flask.make_response).\n\nAccessing Google APIs\n\nThe example below uses [Cloud\nPub/Sub](//cloud.google.com/pubsub/docs/reference/libraries), but this approach\nalso works for other client libraries---for example, [Cloud Natural\nLanguage](//cloud.google.com/natural-language/docs/reference/libraries) or\n[Cloud Spanner](//cloud.google.com/spanner/docs/reference/libraries). Note that\nperformance improvements may depend on the current implementation of particular\nclient libraries.\n\nCreating a Pub/Sub client object results in one connection and two DNS queries\nper invocation. To avoid unnecessary connections and DNS queries, create the\nPub/Sub client object in global scope as shown in the sample below: \n\nnode.js \n\n```javascript\nconst PubSub = require('@google-cloud/pubsub');\nconst functions = require('firebase-functions');\nconst pubsub = PubSub();\n\nexports.function = functions.https.onRequest((req, res) =\u003e {\n const topic = pubsub.topic('');\n\n topic.publish('Test message', 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\nPython \n\n```python\nimport os\n\nfrom firebase_functions import https_fn\nfrom google.cloud import pubsub_v1\n\n# from firebase_functions import https_fn\n# Create a global Pub/Sub client to avoid unneeded network activity\npubsub = pubsub_v1.PublisherClient()\n\n@https_fn.on_request()\ndef gcp_api_call(request):\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.publish(topic_path, data=data)\n\n return https_fn.Response(\"1 message published\")\n \n```\n\nThis HTTP function uses a cached client library instance to reduce the\nnumber of connections required per function invocation. It takes a request\nobject (`flask.Request`) and returns the response text, or any set of values\nthat can be turned into a `Response` object using\n[`make_response`](https://flask.palletsprojects.com/en/3.0.x/api/#flask.make_response).\n\nThe `GCP_PROJECT` environment variable is set automatically in the Python\n3.7 runtime. In later runtimes, make sure to specify it on function\ndeployment. See [Configure environment\nvariables](https://cloud.google.com/run/docs/configuring/services/environment-variables).\n\nOutbound connections\n\nOutbound request timeouts\n\nThere is a timeout after 10 minutes of idle time for requests from your function\nto the VPC network. For requests from your function to the internet, there is a\ntimeout after 20 minutes of idle time.\n\nOutbound connection resets\n\nConnection streams from your function to both the [VPC\nnetwork](https://cloud.google.com/run/docs/configuring/connecting-vpc) and\ninternet can be occasionally terminated and replaced when underlying\ninfrastructure is restarted or updated. If your application reuses long-lived\nconnections, we recommend that you configure your application to re-establish\nconnections to avoid the reuse of a dead connection.\n\nLoad-testing Your Function\n\nTo measure how many connections your function performs on average, deploy\nit as a HTTP function and use a performance-testing framework to invoke it at\ncertain QPS. One possible choice is [Artillery](https://artillery.io/), which\nyou can invoke with a single line: \n\n```\n$ artillery quick -d 300 -r 30 URL\n```\n\nThis command fetches the given URL at 30 QPS for 300 seconds.\n\nAfter performing the test, check the usage of your connection quota on the [Cloud Functions API quota\npage](https://console.cloud.google.com/apis/api/cloudfunctions.googleapis.com/quotas) in Cloud\nConsole. If the usage is consistently around 30 (or its multiple), you are\nestablishing one (or several) connections in every invocation. After you\noptimize your code, you should see a few (10-30) connections occur only at the\nbeginning of the test.\n\nYou can also compare the CPU cost before and after the optimization on the CPU\nquota plot on the same page."]]