無狀態
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
變數狀態函式執行個體會 (和不會) 儲存的內容範例。
程式碼範例
Java
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Node.js
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Python
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Ruby
如要驗證 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"]],[],[[["\u003cp\u003eThe code demonstrates how to track the number of times a Cloud Function is executed within a specific instance.\u003c/p\u003e\n"],["\u003cp\u003eEach function instance maintains its own count, meaning the total invocations across all instances may not be reflected by an individual instance's count.\u003c/p\u003e\n"],["\u003cp\u003eGlobal or static variables are used to store the execution count within a single instance, but they are not shared across instances.\u003c/p\u003e\n"],["\u003cp\u003eThe examples cover C#, Go, Java, Node.js, Python, and Ruby, showcasing a similar approach in each language for instance-specific counting.\u003c/p\u003e\n"],["\u003cp\u003eCloud Run function authentication can be set up using Application Default Credentials, as detailed in the linked documentation.\u003c/p\u003e\n"]]],[],null,["# Statelessness\n\nAn example of what variable state function instances do (and don't) store.\n\nCode sample\n-----------\n\n### C#\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 using Google.Cloud.Functions.Framework;\n using Microsoft.AspNetCore.Http;\n using System.Threading;\n using System.Threading.Tasks;\n\n namespace ExecutionCount;\n\n public class Function : IHttpFunction\n {\n // Note that this variable must be static, because a new instance is\n // created for each request. An alternative approach would be to use\n // dependency injection with a singleton resource injected into the function\n // constructor.\n private static int _count;\n\n public async Task HandleAsync(HttpContext context)\n {\n // Note: the total function invocation count across\n // all servers may not be equal to this value!\n int currentCount = Interlocked.Increment(ref _count);\n await context.Response.WriteAsync($\"Server execution count: {currentCount}\", context.RequestAborted);\n }\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\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n // count is a global variable, but only shared within a function instance.\n var count = 0\n\n func init() {\n \tfunctions.HTTP(\"ExecutionCount\", ExecutionCount)\n }\n\n // ExecutionCount is an HTTP Cloud Function that counts how many times it\n // is executed within a specific instance.\n func ExecutionCount(w http.ResponseWriter, r *http.Request) {\n \tcount++\n\n \t// Note: the total function invocation count across\n \t// all instances may not be equal to this value!\n \tfmt.Fprintf(w, \"Instance execution count: %d\", count)\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.BufferedWriter;\n import java.io.IOException;\n import java.util.concurrent.atomic.AtomicInteger;\n\n public class ExecutionCount implements HttpFunction {\n\n private final AtomicInteger count = new AtomicInteger(0);\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException {\n count.getAndIncrement();\n\n // Note: the total function invocation count across\n // all instances may not be equal to this value!\n BufferedWriter writer = response.getWriter();\n writer.write(\"Instance execution count: \" + count);\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 functions = require('@google-cloud/functions-framework');\n\n // Global variable, but only shared within function instance.\n let count = 0;\n\n /**\n * HTTP Cloud Function that counts how many times\n * it is executed within a specific instance.\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('executionCount', (req, res) =\u003e {\n count++;\n\n // Note: the total function invocation count across\n // all instances may not be equal to this value!\n res.send(`Instance execution count: ${count}`);\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\n\n # Global variable, modified within the function by using the global keyword.\n count = 0\n\n\n @functions_framework.http\n def statelessness(request):\n \"\"\"\n HTTP Cloud Function that counts how many times it is executed\n within a specific instance.\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 count\n count += 1\n\n # Note: the total function invocation count across\n # all instances may not be equal to this value!\n return f\"Instance execution count: {count}\"\n\n### Ruby\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 require \"functions_framework\"\n\n # Global variable, but scoped only within one function instance.\n $count = 0\n\n FunctionsFramework.http \"execution_count\" do |_request|\n $count += 1\n\n # NOTE: the total function invocation count across all instances\n # may not be equal to this value!\n \"Instance execution count: #{$count}\"\n end\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)."]]