延遲變數初始化
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
針對 Cloud Run 服務不常需要記憶體配置和回應延遲影響作業的情況,示範如何延遲初始化值。
深入探索
如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:
程式碼範例
Java
如要向 Cloud Run 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Node.js
如要向 Cloud Run 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Python
如要向 Cloud Run 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。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"]],[],[],[],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)."]]