使用 HTTP 连接池
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
演示如何使用 HTTP 连接池回收 HTTP 连接。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
Go
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
Java
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
Node.js
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
Python
如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。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 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)."]]