지연 변수 초기화
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Cloud Run 서비스에서 메모리 할당 및 응답 지연 시간에 영향을 미치는 작업이 자주 필요하지 않는 경우에 지연된 값 초기화의 사용에 대해 설명합니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
Go
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Java
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Node.js
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Python
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 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"]],[],[],[],null,["# Lazy variable initialization\n\nDemonstrate the use of lazy initialization of values for cases where memory allocation and response latency impacting operations are not commonly needed by the Cloud Run service.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [General development tips](/anthos/run/archive/docs/tips/general)\n- [General development tips](/kubernetes-engine/enterprise/knative-serving/docs/tips/general)\n- [General development tips](/run/docs/tips/general)\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Cloud Run, 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 tips contains tips for writing Cloud Functions in Go.\n package tips\n\n import (\n \t\"context\"\n \t\"log\"\n \t\"net/http\"\n \t\"sync\"\n\n \t\"cloud.google.com/go/storage\"\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n // client is lazily initialized by LazyGlobal.\n var client *storage.Client\n var clientOnce sync.Once\n\n func init() {\n \tfunctions.HTTP(\"LazyGlobal\", LazyGlobal)\n }\n\n // LazyGlobal is an example of lazily initializing a Google Cloud Storage client.\n func LazyGlobal(w http.ResponseWriter, r *http.Request) {\n \t// You may wish to add different checks to see if the client is needed for\n \t// this request.\n \tclientOnce.Do(func() {\n \t\t// Pre-declare an err variable to avoid shadowing client.\n \t\tvar err error\n \t\tclient, err = storage.NewClient(context.Background())\n \t\tif err != nil {\n \t\t\thttp.Error(w, \"Internal error\", http.StatusInternalServerError)\n \t\t\tlog.Printf(\"storage.NewClient: %v\", err)\n \t\t\treturn\n \t\t}\n \t})\n \t// Use client.\n }\n\n### Java\n\n\nTo authenticate to Cloud Run, 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.util.Arrays;\n\n public class LazyFields implements HttpFunction {\n // Always initialized (at cold-start)\n // Warning: Class variables used in Servlet classes must be thread-safe,\n // or else might introduce race conditions in your code.\n private static final int NON_LAZY_GLOBAL = fileWideComputation();\n\n // Declared at cold-start, but only initialized if/when the function executes\n // Uses the \"initialization-on-demand holder\" idiom\n // More information: https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom\n private static class LazyGlobalHolder {\n // Making the default constructor private prohibits instantiation of this class\n private LazyGlobalHolder() {}\n\n // This value is initialized only if (and when) the getLazyGlobal() function below is called\n private static final Integer INSTANCE = functionSpecificComputation();\n\n private static Integer getInstance() {\n return LazyGlobalHolder.INSTANCE;\n }\n }\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException {\n Integer lazyGlobal = LazyGlobalHolder.getInstance();\n\n var writer = new PrintWriter(response.getWriter());\n writer.printf(\"Lazy global: %s; non-lazy global: %s%n\", lazyGlobal, NON_LAZY_GLOBAL);\n }\n\n private static int functionSpecificComputation() {\n int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};\n return Arrays.stream(numbers).sum();\n }\n\n private static int fileWideComputation() {\n int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};\n return Arrays.stream(numbers).reduce((t, x) -\u003e t * x).getAsInt();\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run, 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 functions = require('@google-cloud/functions-framework');\n\n // Always initialized (at cold-start)\n const nonLazyGlobal = fileWideComputation();\n\n // Declared at cold-start, but only initialized if/when the function executes\n let lazyGlobal;\n\n /**\n * HTTP function that uses lazy-initialized globals\n *\n * @param {Object} req request context.\n * @param {Object} res response context.\n */\n functions.http('lazyGlobals', (req, res) =\u003e {\n // This value is initialized only if (and when) the function is called\n lazyGlobal = lazyGlobal || functionSpecificComputation();\n\n res.send(`Lazy global: ${lazyGlobal}, non-lazy global: ${nonLazyGlobal}`);\n });\n\n### Python\n\n\nTo authenticate to Cloud Run, 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\n # Always initialized (at cold-start)\n non_lazy_global = file_wide_computation()\n\n # Declared at cold-start, but only initialized if/when the function executes\n lazy_global = None\n\n\n @functions_framework.http\n def lazy_globals(request):\n \"\"\"\n HTTP Cloud Function that uses lazily-initialized globals.\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 global lazy_global, non_lazy_global # noqa: F824\n\n # This value is initialized only if (and when) the function is called\n if not lazy_global:\n lazy_global = function_specific_computation()\n\n return f\"Lazy: {lazy_global}, non-lazy: {non_lazy_global}.\"\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=cloudrun)."]]