Zustandslosigkeit

Ein Beispiel dafür, was von Funktionsinstanzen mit variablem Zustand gespeichert (und nicht gespeichert) wird.

Codebeispiel

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Run Functions zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

using Google.Cloud.Functions.Framework;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;

namespace ExecutionCount;

public class Function : IHttpFunction
{
    // Note that this variable must be static, because a new instance is
    // created for each request. An alternative approach would be to use
    // dependency injection with a singleton resource injected into the function
    // constructor.
    private static int _count;

    public async Task HandleAsync(HttpContext context)
    {
        // Note: the total function invocation count across
        // all servers may not be equal to this value!
        int currentCount = Interlocked.Increment(ref _count);
        await context.Response.WriteAsync($"Server execution count: {currentCount}", context.RequestAborted);
    }
}

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Run Functions zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


// Package http provides a set of HTTP Cloud Functions samples.
package http

import (
	"fmt"
	"net/http"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)

// count is a global variable, but only shared within a function instance.
var count = 0

func init() {
	functions.HTTP("ExecutionCount", ExecutionCount)
}

// ExecutionCount is an HTTP Cloud Function that counts how many times it
// is executed within a specific instance.
func ExecutionCount(w http.ResponseWriter, r *http.Request) {
	count++

	// Note: the total function invocation count across
	// all instances may not be equal to this value!
	fmt.Fprintf(w, "Instance execution count: %d", count)
}

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Run Functions zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

public class ExecutionCount implements HttpFunction {

  private final AtomicInteger count = new AtomicInteger(0);

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    count.getAndIncrement();

    // Note: the total function invocation count across
    // all instances may not be equal to this value!
    BufferedWriter writer = response.getWriter();
    writer.write("Instance execution count: " + count);
  }
}

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Run Functions zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

const functions = require('@google-cloud/functions-framework');

// Global variable, but only shared within function instance.
let count = 0;

/**
 * HTTP Cloud Function that counts how many times
 * it is executed within a specific instance.
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
functions.http('executionCount', (req, res) => {
  count++;

  // Note: the total function invocation count across
  // all instances may not be equal to this value!
  res.send(`Instance execution count: ${count}`);
});

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Run Functions zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import functions_framework


# Global variable, modified within the function by using the global keyword.
count = 0


@functions_framework.http
def statelessness(request):
    """
    HTTP Cloud Function that counts how many times it is executed
    within a specific instance.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    global count
    count += 1

    # Note: the total function invocation count across
    # all instances may not be equal to this value!
    return f"Instance execution count: {count}"

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Run Functions zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

require "functions_framework"

# Global variable, but scoped only within one function instance.
$count = 0

FunctionsFramework.http "execution_count" do |_request|
  $count += 1

  # NOTE: the total function invocation count across all instances
  # may not be equal to this value!
  "Instance execution count: #{$count}"
end

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud -Produkte finden Sie im Google Cloud Beispielbrowser.