constfetch=require('node-fetch');consthttp=require('http');consthttps=require('https');constfunctions=require('@google-cloud/functions-framework');consthttpAgent=newhttp.Agent({keepAlive:true});consthttpsAgent=newhttps.Agent({keepAlive:true});/** * HTTP Cloud Function that caches an HTTP agent to pool HTTP connections. * * @param {Object} req Cloud Function request context. * @param {Object} res Cloud Function response context. */functions.http('connectionPooling',async(req,res)=>{try{// TODO(optional): replace this with your own URL.consturl='https://www.example.com/';// Select the appropriate agent to use based on the URL.constagent=url.includes('https')?httpsAgent:httpAgent;constfetchResponse=awaitfetch(url,{agent});consttext=awaitfetchResponse.text();res.status(200).send(`Data: ${text}`);}catch(err){res.status(500).send(`Error: ${err.message}`);}});
Python
importfunctions_frameworkimportrequests# Create a global HTTP session (which provides connection pooling)session=requests.Session()@functions_framework.httpdefconnection_pooling(request):""" HTTP Cloud Function that uses a connection pool to make HTTP requests. Args: request (flask.Request): The request object. <http://flask.pocoo.org/docs/1.0/api/#flask.Request> Returns: The response text, or any set of values that can be turned into a Response object using `make_response` <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>. """# The URL to send the request tourl="http://example.com"# Process the requestresponse=session.get(url)response.raise_for_status()return"Success!"
Go
// Package http provides a set of HTTP Cloud Functions samples.packagehttpimport("fmt""net/http""time""github.com/GoogleCloudPlatform/functions-framework-go/functions")varurlString="https://example.com"// client is used to make HTTP requests with a 10 second timeout.// http.Clients should be reused instead of created as needed.varclient=&http.Client{Timeout:10*time.Second,}funcinit(){functions.HTTP("MakeRequest",MakeRequest)}// MakeRequest is an example of making an HTTP request. MakeRequest uses a// single http.Client for all requests to take advantage of connection// pooling and caching. See https://godoc.org/net/http#Client.funcMakeRequest(whttp.ResponseWriter,r*http.Request){resp,err:=client.Get(urlString)iferr!=nil{http.Error(w,"Error making request",http.StatusInternalServerError)return}ifresp.StatusCode!=http.StatusOK{msg:=fmt.Sprintf("Bad StatusCode: %d",resp.StatusCode)http.Error(w,msg,http.StatusInternalServerError)return}fmt.Fprintf(w,"ok")}
如果创建 Pub/Sub 客户端对象,则每次调用会执行一次连接和两次 DNS 查询。为了避免不必要的连接和 DNS 查询,请按照以下示例所示,在全局范围内创建 Pub/Sub 客户端对象:
Node.js
constfunctions=require('@google-cloud/functions-framework');const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();/** * HTTP Cloud Function that uses a cached client library instance to * reduce the number of connections required per function invocation. * * @param {Object} req Cloud Function request context. * @param {Object} req.body Cloud Function request context body. * @param {String} req.body.topic The Cloud Pub/Sub topic to publish to. * @param {Object} res Cloud Function response context. */functions.http('gcpApiCall',(req,res)=>{consttopic=pubsub.topic(req.body.topic);constdata=Buffer.from('Test message');topic.publishMessage({data},err=>{if(err){res.status(500).send(`Error publishing the message: ${err}`);}else{res.status(200).send('1 message published');}});});
Python
importosimportfunctions_frameworkfromgoogle.cloudimportpubsub_v1# Create a global Pub/Sub client to avoid unneeded network activitypubsub=pubsub_v1.PublisherClient()@functions_framework.httpdefgcp_api_call(request):""" HTTP Cloud Function that uses a cached client library instance to reduce the number of connections required per function invocation. Args: request (flask.Request): The request object. Returns: The response text, or any set of values that can be turned into a Response object using `make_response` <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>. """""" The `GCP_PROJECT` environment variable is set automatically in the Python 3.7 runtime. In later runtimes, it must be specified by the user upon function deployment. See this page for more information: https://cloud.google.com/functions/docs/configuring/env-var#python_37_and_go_111 """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)return"1 message published"
Go
// Package contexttip is an example of how to use Pub/Sub and context.Context in// a Cloud Function.packagecontexttipimport("context""encoding/json""fmt""log""net/http""os""sync""cloud.google.com/go/pubsub""github.com/GoogleCloudPlatform/functions-framework-go/functions")// client is a global Pub/Sub client, initialized once per instance.varclient*pubsub.Clientvaroncesync.Once// createClient creates the global pubsub ClientfunccreateClient(){// GOOGLE_CLOUD_PROJECT is a user-set environment variable.varprojectID=os.Getenv("GOOGLE_CLOUD_PROJECT")// err is pre-declared to avoid shadowing client.varerrerror// client is initialized with context.Background() because it should// persist between function invocations.client,err=pubsub.NewClient(context.Background(),projectID)iferr!=nil{log.Fatalf("pubsub.NewClient: %v",err)}}funcinit(){// register http functionfunctions.HTTP("PublishMessage",PublishMessage)}typepublishRequeststruct{Topicstring`json:"topic"`Messagestring`json:"message"`}// PublishMessage publishes a message to Pub/Sub. PublishMessage only works// with topics that already exist.funcPublishMessage(whttp.ResponseWriter,r*http.Request){// use of sync.Once ensures client is only created once.once.Do(createClient)// Parse the request body to get the topic name and message.p:=publishRequest{}iferr:=json.NewDecoder(r.Body).Decode(&p);err!=nil{log.Printf("json.NewDecoder: %v",err)http.Error(w,"Error parsing request",http.StatusBadRequest)return}ifp.Topic==""||p.Message==""{s:="missing 'topic' or 'message' parameter"log.Println(s)http.Error(w,s,http.StatusBadRequest)return}m:=&pubsub.Message{Data:[]byte(p.Message),}// Publish and Get use r.Context() because they are only needed for this// function invocation. If this were a background function, they would use// the ctx passed as an argument.id,err:=client.Topic(p.Topic).Publish(r.Context(),m).Get(r.Context())iferr!=nil{log.Printf("topic(%s).Publish.Get: %v",p.Topic,err)http.Error(w,"Error publishing message",http.StatusInternalServerError)return}fmt.Fprintf(w,"Message published: %v",id)}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2024-11-20。"],[[["This document outlines networking optimization strategies specifically for Cloud Run functions (1st gen), which is crucial for scalability and cost-effectiveness."],["Maintaining persistent connections, rather than creating new ones for each function invocation, significantly reduces CPU time and minimizes the risk of exceeding connection or DNS quotas."],["For HTTP/S requests, using persistent connection pooling, as demonstrated in the Node.js, Python, Go, and PHP examples, is essential to optimizing connection management."],["When interacting with Google APIs, like Cloud Pub/Sub, creating client objects in global scope avoids unnecessary connection and DNS queries, which also leads to more optimized networking performance."],["It is important to load test your functions to measure connection usage, and if you see connection resets, re-establish them to avoid dead connections, optimizing your function's overall performance."]]],[]]