Caractéristique "sans état"
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cette page fournit un exemple de ce que les instances de fonction à état variable stockent (ou ne stockent pas).
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","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)."]]