Utilizzo del pool di connessioni HTTP
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Mostra come riciclare le connessioni HTTP utilizzando i pool di connessioni HTTP.
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 page demonstrates how to effectively recycle HTTP connections by using HTTP connection pools in various languages.\u003c/p\u003e\n"],["\u003cp\u003eReusing \u003ccode\u003ehttp.Client\u003c/code\u003e or \u003ccode\u003eHttpClient\u003c/code\u003e instances is shown to be an effective way to leverage connection pooling and caching for improved performance.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code samples illustrate using \u003ccode\u003ehttp.Agent\u003c/code\u003e (Node.js), \u003ccode\u003erequests.Session\u003c/code\u003e (Python), and \u003ccode\u003ejava.net.http.HttpClient\u003c/code\u003e (Java) to establish persistent connections for subsequent HTTP requests.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples also showcase how to properly set up authentication for Cloud Run functions using Application Default Credentials.\u003c/p\u003e\n"]]],[],null,["# Use HTTP connection pooling\n\nShows how to recycle HTTP connections using HTTP connection pools.\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### Go\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\n // Package http provides a set of HTTP Cloud Functions samples.\n package http\n\n import (\n \t\"fmt\"\n \t\"net/http\"\n \t\"time\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n var urlString = \"https://example.com\"\n\n // client is used to make HTTP requests with a 10 second timeout.\n // http.Clients should be reused instead of created as needed.\n var client = &http.Client{\n \tTimeout: 10 * time.Second,\n }\n\n func init() {\n \tfunctions.HTTP(\"MakeRequest\", MakeRequest)\n }\n\n // MakeRequest is an example of making an HTTP request. MakeRequest uses a\n // single http.Client for all requests to take advantage of connection\n // pooling and caching. See https://godoc.org/net/http#Client.\n func MakeRequest(w http.ResponseWriter, r *http.Request) {\n \tresp, err := client.Get(urlString)\n \tif err != nil {\n \t\thttp.Error(w, \"Error making request\", http.StatusInternalServerError)\n \t\treturn\n \t}\n \tif resp.StatusCode != http.StatusOK {\n \t\tmsg := fmt.Sprintf(\"Bad StatusCode: %d\", resp.StatusCode)\n \t\thttp.Error(w, msg, http.StatusInternalServerError)\n \t\treturn\n \t}\n \tfmt.Fprintf(w, \"ok\")\n }\n\n### Java\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\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.IOException;\n import java.io.PrintWriter;\n import java.net.URI;\n import java.net.http.HttpClient;\n import java.net.http.HttpResponse.BodyHandlers;\n import java.time.Duration;\n\n public class SendHttpRequest implements HttpFunction {\n\n // Create a client with some reasonable defaults. This client can be reused for multiple requests.\n // (java.net.httpClient also pools connections automatically by default.)\n private static HttpClient client =\n HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException, InterruptedException {\n // Create a GET sendHttpRequest to \"http://example.com\"\n String url = \"http://example.com\";\n var getRequest = java.net.http.HttpRequest.newBuilder().uri(URI.create(url)).GET().build();\n\n // Send the sendHttpRequest using the client\n var getResponse = client.send(getRequest, BodyHandlers.ofString());\n\n // Write the results to the output:\n var writer = new PrintWriter(response.getWriter());\n writer.printf(\"Received code '%s' from url '%s'.\", getResponse.statusCode(), url);\n }\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 fetch = require('node-fetch');\n\n const http = require('http');\n const https = require('https');\n\n const functions = require('@google-cloud/functions-framework');\n\n const httpAgent = new http.Agent({keepAlive: true});\n const httpsAgent = new https.Agent({keepAlive: true});\n\n /**\n * HTTP Cloud Function that caches an HTTP agent to pool HTTP connections.\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('connectionPooling', async (req, res) =\u003e {\n try {\n // TODO(optional): replace this with your own URL.\n const url = 'https://www.example.com/';\n\n // Select the appropriate agent to use based on the URL.\n const agent = url.includes('https') ? httpsAgent : httpAgent;\n\n const fetchResponse = await fetch(url, {agent});\n const text = await fetchResponse.text();\n\n res.status(200).send(`Data: ${text}`);\n } catch (err) {\n res.status(500).send(`Error: ${err.message}`);\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 functions_framework\n import requests\n\n # Create a global HTTP session (which provides connection pooling)\n session = requests.Session()\n\n\n @functions_framework.http\n def connection_pooling(request):\n \"\"\"\n HTTP Cloud Function that uses a connection pool to make HTTP requests.\n Args:\n request (flask.Request): The request object.\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Request\u003e\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 # 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 \"Success!\"\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)."]]