새 함수를 만드는 경우 Cloud Run의
콘솔 빠른 시작을 참고하세요.
HTTP 연결 풀링 사용
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
HTTP 연결 풀을 사용하여 HTTP 연결을 재사용하는 방법을 보여줍니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
Go
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Java
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Node.js
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Python
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 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)."]]