HTTP-Zielaufgaben erstellen

Cloud Tasks-Handler können auf jedem HTTP-Endpunkt mit einer externen IP-Adresse wie GKE, Compute Engine oder sogar auf einem lokalen Webserver ausgeführt werden. Ihre Aufgaben können auf zuverlässige, konfigurierbare Weise in jedem dieser Dienste ausgeführt werden.

Auf dieser Seite wird gezeigt, wie grundlegende HTTP-Zielaufgaben programmatisch erstellt und in Cloud Tasks-Warteschlangen platziert werden.

Für Aufgaben mit HTTP-Zielen (im Gegensatz zu expliziten, weniger gängigen App Engine-Zielen) gibt es zwei Möglichkeiten, Aufgaben zu erstellen:

  • BufferTask-Methode: Verwenden Sie diese Methode, wenn Ihre Warteschlange so eingerichtet ist, dass Aufgaben vor einem Dienst zwischengespeichert werden. Die Warteschlange muss ein Routing auf Warteschlangenebene haben. Für die meisten Anwendungsfälle ist dies der beste Ansatz. Bei diesem Ansatz wird die Methode BufferTask verwendet.

  • CreateTask-Methode:Diese Methode ist komplexer. Sie müssen explizit ein Aufgabenobjekt erstellen. Verwenden Sie diese Methode, wenn die Aufgaben in Ihrer Warteschlange unterschiedliche Routingkonfigurationen haben. In diesem Fall legen Sie das Routing auf Aufgabenebene fest und können kein Routing auf Warteschlangenebene verwenden. Bei diesem Ansatz wird die Methode CreateTask verwendet.

Grundlegende Aufgabenerstellung (Methode BufferTask)

In diesem Abschnitt wird beschrieben, wie Sie eine Aufgabe durch Senden einer HTTP-Anfrage erstellen. Die von Ihnen verwendete Methode heißt BufferTask.

Beschränkungen

Die Methode BufferTask unterliegt den folgenden Einschränkungen:

  • Clientbibliotheken:Die Methode BufferTask wird in Clientbibliotheken nicht unterstützt.

  • RPC API:Die Methode BufferTask wird in der RPC API nicht unterstützt.

  • Routing auf Aufgabenebene: Diese Methode unterstützt kein Routing auf Aufgabenebene. Da beim Erstellen einer Aufgabe auf diese Weise keine Routinginformationen hinzugefügt werden können, müssen Sie das Routing auf Warteschlangenebene verwenden. Andernfalls hat die Aufgabe keine Routinginformationen. Wenn die Warteschlange noch kein Routing auf Warteschlangenebene verwendet, finden Sie weitere Informationen unter Routing auf Warteschlangenebene für HTTP-Aufgaben konfigurieren.

Methode BufferTask aufrufen

Die folgenden Beispiele zeigen, wie Sie eine Aufgabe durch Senden einer HTTP-POST-Anfrage an den buffer-Endpunkt der Cloud Tasks API erstellen.

Python

from google.cloud import tasks_v2beta3 as tasks

import requests


def send_task_to_http_queue(
    queue: tasks.Queue, body: str = "", token: str = "", headers: dict = {}
) -> int:
    """Send a task to an HTTP queue.
    Args:
        queue: The queue to delete.
        body: The body of the task.
        auth_token: An authorization token for the queue.
        headers: Headers to set on the task.
    Returns:
        The matching queue, or None if it does not exist.
    """

    # Use application default credentials if not supplied in a header
    if token:
        headers["Authorization"] = f"Bearer {token}"

    endpoint = f"https://cloudtasks.googleapis.com/v2beta3/{queue.name}/tasks:buffer"
    response = requests.post(endpoint, body, headers=headers)

    return response.status_code

curl

Das folgende Code-Snippet zeigt ein Beispiel für die Aufgabenerstellung mit der Methode BufferTask und curl:

curl -X HTTP_METHOD\
"https://cloudtasks.googleapis.com/v2/projects/PROJECT_ID/locations/LOCATION/queues/QUEUE_ID/tasks:buffer" \

Ersetzen Sie Folgendes:

  • HTTP_METHOD: Die HTTP-Methode für Ihre Anfrage, z. B. GET oder POST.
  • PROJECT_ID: ID Ihres Google Cloud-Projekts. Sie können sie abrufen, indem Sie Folgendes in Ihrem Terminal ausführen:
    gcloud config get-value project
  • LOCATION: Der Speicherort deiner Warteschlange.
  • QUEUE_ID: Die ID der Warteschlange.

Erweiterte Aufgabenerstellung (Methode CreateTask)

In diesem Abschnitt wird erläutert, wie Sie eine Aufgabe mithilfe des Aufgabenobjekts erstellen. Dazu verwenden Sie die Methode CreateTask.

Wenn Sie eine Aufgabe mit der Methode CreateTask erstellen, wird das Aufgabenobjekt explizit erstellt und definiert. Sie müssen den Dienst und den Handler angeben, die die Aufgabe verarbeiten.

Optional können Sie aufgabenspezifische Daten an den Handler übergeben. Sie können auch die Konfiguration für die Aufgabe optimieren, z. B. einen Zeitpunkt in der Zukunft festlegen, zu dem die Aufgabe ausgeführt werden soll, oder die Anzahl der Wiederholungen beschränken, wenn die Aufgabe fehlschlägt (siehe Erweiterte Konfiguration).

In den folgenden Beispielen wird die Methode CreateTask aufgerufen, um mithilfe der Cloud Tasks-Clientbibliotheken eine Aufgabe zu erstellen.

C#


using Google.Cloud.Tasks.V2;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using System;

class CreateHttpTask
{
    public string CreateTask(
        string projectId = "YOUR-PROJECT-ID",
        string location = "us-central1",
        string queue = "my-queue",
        string url = "http://example.com/taskhandler",
        string payload = "Hello World!",
        int inSeconds = 0)
    {
        CloudTasksClient client = CloudTasksClient.Create();
        QueueName parent = new QueueName(projectId, location, queue);

        var response = client.CreateTask(new CreateTaskRequest
        {
            Parent = parent.ToString(),
            Task = new Task
            {
                HttpRequest = new HttpRequest
                {
                    HttpMethod = HttpMethod.Post,
                    Url = url,
                    Body = ByteString.CopyFromUtf8(payload)
                },
                ScheduleTime = Timestamp.FromDateTime(
                    DateTime.UtcNow.AddSeconds(inSeconds))
            }
        });

        Console.WriteLine($"Created Task {response.Name}");
        return response.Name;
    }
}

Python

import datetime
import json
from typing import Dict, Optional

from google.cloud import tasks_v2
from google.protobuf import duration_pb2, timestamp_pb2


def create_http_task(
    project: str,
    location: str,
    queue: str,
    url: str,
    json_payload: Dict,
    scheduled_seconds_from_now: Optional[int] = None,
    task_id: Optional[str] = None,
    deadline_in_seconds: Optional[int] = None,
) -> tasks_v2.Task:
    """Create an HTTP POST task with a JSON payload.
    Args:
        project: The project ID where the queue is located.
        location: The location where the queue is located.
        queue: The ID of the queue to add the task to.
        url: The target URL of the task.
        json_payload: The JSON payload to send.
        scheduled_seconds_from_now: Seconds from now to schedule the task for.
        task_id: ID to use for the newly created task.
        deadline_in_seconds: The deadline in seconds for task.
    Returns:
        The newly created task.
    """

    # Create a client.
    client = tasks_v2.CloudTasksClient()

    # Construct the task.
    task = tasks_v2.Task(
        http_request=tasks_v2.HttpRequest(
            http_method=tasks_v2.HttpMethod.POST,
            url=url,
            headers={"Content-type": "application/json"},
            body=json.dumps(json_payload).encode(),
        ),
        name=(
            client.task_path(project, location, queue, task_id)
            if task_id is not None
            else None
        ),
    )

    # Convert "seconds from now" to an absolute Protobuf Timestamp
    if scheduled_seconds_from_now is not None:
        timestamp = timestamp_pb2.Timestamp()
        timestamp.FromDatetime(
            datetime.datetime.utcnow()
            + datetime.timedelta(seconds=scheduled_seconds_from_now)
        )
        task.schedule_time = timestamp

    # Convert "deadline in seconds" to a Protobuf Duration
    if deadline_in_seconds is not None:
        duration = duration_pb2.Duration()
        duration.FromSeconds(deadline_in_seconds)
        task.dispatch_deadline = duration

    # Use the client to send a CreateTaskRequest.
    return client.create_task(
        tasks_v2.CreateTaskRequest(
            # The queue to add the task to
            parent=client.queue_path(project, location, queue),
            # The task itself
            task=task,
        )
    )

Beachten Sie die Datei requirements.txt:

google-cloud-tasks==2.13.1

Java

import com.google.cloud.tasks.v2.CloudTasksClient;
import com.google.cloud.tasks.v2.HttpMethod;
import com.google.cloud.tasks.v2.HttpRequest;
import com.google.cloud.tasks.v2.QueueName;
import com.google.cloud.tasks.v2.Task;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.charset.Charset;

public class CreateHttpTask {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String locationId = "us-central1";
    String queueId = "my-queue";
    createTask(projectId, locationId, queueId);
  }

  // Create a task with a HTTP target using the Cloud Tasks client.
  public static void createTask(String projectId, String locationId, String queueId)
      throws IOException {

    // Instantiates a client.
    try (CloudTasksClient client = CloudTasksClient.create()) {
      String url = "https://example.com/taskhandler";
      String payload = "Hello, World!";

      // Construct the fully qualified queue name.
      String queuePath = QueueName.of(projectId, locationId, queueId).toString();

      // Construct the task body.
      Task.Builder taskBuilder =
          Task.newBuilder()
              .setHttpRequest(
                  HttpRequest.newBuilder()
                      .setBody(ByteString.copyFrom(payload, Charset.defaultCharset()))
                      .setUrl(url)
                      .setHttpMethod(HttpMethod.POST)
                      .build());

      // Send create task request.
      Task task = client.createTask(queuePath, taskBuilder.build());
      System.out.println("Task created: " + task.getName());
    }
  }
}

Beachten Sie die Datei pom.xml:

<?xml version='1.0' encoding='UTF-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.tasks</groupId>
  <artifactId>cloudtasks-snippets</artifactId>
  <packaging>jar</packaging>
  <name>Google Cloud Tasks Snippets</name>

  <!--
    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>


  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>libraries-bom</artifactId>
        <version>26.32.0</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-tasks</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.truth</groupId>
      <artifactId>truth</artifactId>
      <version>1.4.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

PHP

use Google\Cloud\Tasks\V2\Client\CloudTasksClient;
use Google\Cloud\Tasks\V2\CreateTaskRequest;
use Google\Cloud\Tasks\V2\HttpMethod;
use Google\Cloud\Tasks\V2\HttpRequest;
use Google\Cloud\Tasks\V2\Task;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $locationId = 'The Location ID';
// $queueId = 'The Cloud Tasks Queue ID';
// $url = 'The full url path that the task request will be sent to.'
// $payload = 'The payload your task should carry to the task handler. Optional';

// Instantiate the client and queue name.
$client = new CloudTasksClient();
$queueName = $client->queueName($projectId, $locationId, $queueId);

// Create an Http Request Object.
$httpRequest = new HttpRequest();
// The full url path that the task request will be sent to.
$httpRequest->setUrl($url);
// POST is the default HTTP method, but any HTTP method can be used.
$httpRequest->setHttpMethod(HttpMethod::POST);
// Setting a body value is only compatible with HTTP POST and PUT requests.
if (!empty($payload)) {
    $httpRequest->setBody($payload);
}

// Create a Cloud Task object.
$task = new Task();
$task->setHttpRequest($httpRequest);

// Send request and print the task name.
$request = (new CreateTaskRequest())
    ->setParent($queueName)
    ->setTask($task);
$response = $client->createTask($request);
printf('Created task %s' . PHP_EOL, $response->getName());

Beachten Sie die Datei composer.json:

{
    "require": {
        "google/cloud-tasks": "^1.14"
    }
}

Einfach loslegen (Go)


// Command createHTTPtask constructs and adds a task to a Cloud Tasks Queue.
package main

import (
	"context"
	"fmt"

	cloudtasks "cloud.google.com/go/cloudtasks/apiv2"
	taskspb "cloud.google.com/go/cloudtasks/apiv2/cloudtaskspb"
)

// createHTTPTask creates a new task with a HTTP target then adds it to a Queue.
func createHTTPTask(projectID, locationID, queueID, url, message string) (*taskspb.Task, error) {

	// Create a new Cloud Tasks client instance.
	// See https://godoc.org/cloud.google.com/go/cloudtasks/apiv2
	ctx := context.Background()
	client, err := cloudtasks.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	// Build the Task queue path.
	queuePath := fmt.Sprintf("projects/%s/locations/%s/queues/%s", projectID, locationID, queueID)

	// Build the Task payload.
	// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#CreateTaskRequest
	req := &taskspb.CreateTaskRequest{
		Parent: queuePath,
		Task: &taskspb.Task{
			// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#HttpRequest
			MessageType: &taskspb.Task_HttpRequest{
				HttpRequest: &taskspb.HttpRequest{
					HttpMethod: taskspb.HttpMethod_POST,
					Url:        url,
				},
			},
		},
	}

	// Add a payload message if one is present.
	req.Task.GetHttpRequest().Body = []byte(message)

	createdTask, err := client.CreateTask(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("cloudtasks.CreateTask: %w", err)
	}

	return createdTask, nil
}

Node.js

// Imports the Google Cloud Tasks library.
const {CloudTasksClient} = require('@google-cloud/tasks');

// Instantiates a client.
const client = new CloudTasksClient();

async function createHttpTask() {
  // TODO(developer): Uncomment these lines and replace with your values.
  // const project = 'my-project-id';
  // const queue = 'my-queue';
  // const location = 'us-central1';
  // const url = 'https://example.com/taskhandler';
  // const payload = 'Hello, World!';
  // const inSeconds = 180;

  // Construct the fully qualified queue name.
  const parent = client.queuePath(project, location, queue);

  const task = {
    httpRequest: {
      headers: {
        'Content-Type': 'text/plain', // Set content type to ensure compatibility your application's request parsing
      },
      httpMethod: 'POST',
      url,
    },
  };

  if (payload) {
    task.httpRequest.body = Buffer.from(payload).toString('base64');
  }

  if (inSeconds) {
    // The time when the task is scheduled to be attempted.
    task.scheduleTime = {
      seconds: parseInt(inSeconds) + Date.now() / 1000,
    };
  }

  // Send create task request.
  console.log('Sending task:');
  console.log(task);
  const request = {parent: parent, task: task};
  const [response] = await client.createTask(request);
  console.log(`Created task ${response.name}`);
}
createHttpTask();

Beachten Sie die Datei package.json:

{
  "name": "appengine-cloudtasks",
  "description": "Google App Engine Cloud Tasks example.",
  "license": "Apache-2.0",
  "author": "Google Inc.",
  "private": true,
  "engines": {
    "node": ">=16.0.0"
  },
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "c8 mocha -p -j 2 --timeout 30000",
    "start": "node server.js"
  },
  "dependencies": {
    "@google-cloud/tasks": "^4.0.0",
    "express": "^4.16.3"
  },
  "devDependencies": {
    "c8": "^8.0.0",
    "chai": "^4.2.0",
    "mocha": "^10.0.0",
    "uuid": "^9.0.0"
  }
}

Ruby

require "google/cloud/tasks"

# Create a Task with an HTTP Target
#
# @param [String] project_id Your Google Cloud Project ID.
# @param [String] location_id Your Google Cloud Project Location ID.
# @param [String] queue_id Your Google Cloud Tasks Queue ID.
# @param [String] url The full path to sent the task request to.
# @param [String] payload The request body of your task.
# @param [Integer] seconds The delay, in seconds, to process your task.
def create_http_task project_id, location_id, queue_id, url, payload: nil, seconds: nil
  # Instantiates a client.
  client = Google::Cloud::Tasks.cloud_tasks

  # Construct the fully qualified queue name.
  parent = client.queue_path project: project_id, location: location_id, queue: queue_id

  # Construct task.
  task = {
    http_request: {
      http_method: "POST",
      url:         url
    }
  }

  # Add payload to task body.
  task[:http_request][:body] = payload if payload

  # Add scheduled time to task.
  if seconds
    timestamp = Google::Protobuf::Timestamp.new
    timestamp.seconds = Time.now.to_i + seconds.to_i
    task[:schedule_time] = timestamp
  end

  # Send create task request.
  puts "Sending task #{task}"

  response = client.create_task parent: parent, task: task

  puts "Created task #{response.name}" if response.name
end

Dienstkonten für die HTTP-Ziel-Handler-Authentifizierung einrichten

Cloud Tasks kann HTTP-Ziel-Handler aufrufen, die eine Authentifizierung erfordern, wenn Sie ein Dienstkonto mit den entsprechenden Anmeldedaten für den Zugriff auf den Handler haben.

Wenn Sie ein aktuelles Dienstkonto haben, das Sie verwenden möchten, können Sie das tun. Gewähren Sie ihm einfach die entsprechenden Rollen. In dieser Anleitung wird das Erstellen eines neuen Dienstkontos speziell für diese Funktion beschrieben. Das vorhandene oder neue Dienstkonto, das für die Cloud Tasks-Authentifizierung verwendet wird, muss sich im selben Projekt wie Ihre Cloud Tasks-Warteschlangen befinden.

  1. Rufen Sie in der Google Cloud Console die Seite Dienstkonten auf:

    Zur Seite „Dienstkonten“

  2. Wählen Sie bei Bedarf das entsprechende Projekt aus.

  3. Klicken Sie auf Dienstkonto erstellen.

  4. Geben Sie im Abschnitt Dienstkontodetails einen Namen für das Konto ein. In der Console wird ein zugehöriger E-Mail-Kontoname für das Konto erstellt. So verweisen Sie auf das Konto. Sie können auch eine Beschreibung des Zwecks des Kontos hinzufügen. Klicken Sie auf Erstellen und fortfahren.

  5. Klicken Sie im Abschnitt Diesem Dienstkonto Zugriff auf das Projekt gewähren auf Rolle auswählen. Suchen Sie nach Cloud Tasks-Ersteller und wählen Sie ihn aus. Diese Rolle gewährt dem Dienstkonto die Berechtigung, Aufgaben zur Warteschlange hinzuzufügen.

  6. Klicken Sie auf + Weitere Rolle hinzufügen.

  7. Klicken Sie auf Rolle auswählen. Suchen Sie nach Dienstkontonutzer und wählen Sie die Option aus. Mit dieser Rolle kann das Dienstkonto die Warteschlange autorisieren, in seinem Namen Tokens mithilfe der Anmeldedaten des Dienstkontos zu erstellen.

  8. Wenn Ihr Handler Teil von Google Cloud ist, weisen Sie dem Dienstkonto die Rolle zu, die mit dem Zugriff auf den Dienst verknüpft ist, auf dem der Handler ausgeführt wird. Jeder Dienst innerhalb von Google Cloud benötigt eine andere Rolle. Um beispielsweise auf einen Handler in Cloud Run zuzugreifen, ist die Rolle Cloud Run Invoker erforderlich usw. Sie können das gerade erstellte Dienstkonto oder ein anderes Dienstkonto in Ihrem Projekt verwenden.

  9. Klicken Sie auf Fertig, um das Erstellen des Dienstkontos abzuschließen.

Cloud Tasks selbst muss ein eigenes Dienstkonto haben, dem die Rolle Cloud Tasks Service Agent zugewiesen ist. Auf diese Weise können Header-Tokens basierend auf den Anmeldedaten generiert werden, die mit dem Cloud Tasks-Dienstkonto verknüpft sind, um sich bei Ihrem Handler-Ziel zu authentifizieren. Das Cloud Tasks-Dienstkonto mit dieser Rolle wird automatisch erstellt, wenn Sie die Cloud Tasks API aktivieren, es sei denn, Sie haben sie vor dem 19. März 2019 aktiviert. In diesem Fall müssen Sie die Rolle manuell hinzufügen.

HTTP-Zielaufgaben mit Authentifizierungstokens verwenden

Für die Authentifizierung zwischen Cloud Tasks und einem HTTP-Ziel-Handler, der eine solche Authentifizierung erfordert, erstellt Cloud Tasks ein Header-Token. Dieses Token basiert auf den Anmeldedaten im Dienstkonto Cloud Tasks Enqueuer, die durch seine E-Mail-Adresse identifiziert werden. Das für die Authentifizierung verwendete Dienstkonto muss zu demselben Projekt gehören, in dem sich die Cloud Tasks-Warteschlange befindet. Die Anfrage mit dem Headertoken wird über HTTPS aus der Warteschlange an den Handler gesendet. Sie können entweder ein ID-Token oder ein Zugriffstoken verwenden. ID-Tokens sollten im Allgemeinen für jeden Handler verwendet werden, der in Google Cloud ausgeführt wird, z. B. in Cloud Functions oder Cloud Run. Die Hauptausnahme ist für Google APIs, die auf *.googleapis.com gehostet werden: Diese APIs erwarten ein Zugriffstoken.

Sie können die Authentifizierung auf Warteschlangen- oder auf Aufgabenebene konfigurieren. Informationen zum Konfigurieren der Authentifizierung auf Warteschlangenebene finden Sie unter Cloud Tasks-Warteschlangen erstellen. Wenn die Authentifizierung auf Warteschlangenebene konfiguriert ist, überschreibt diese Konfiguration die Konfiguration auf Aufgabenebene. Wenn Sie die Authentifizierung auf Aufgabenebene konfigurieren möchten, geben Sie in der Aufgabe entweder ein ID-Token (OIDC) oder ein Zugriffstoken (OAuth) an.

Methode BufferTask

In den folgenden Beispielen werden die Standardanmeldedaten der Anwendung zur Authentifizierung verwendet, wenn die Methode BufferTask zum Erstellen einer Aufgabe verwendet wird.

Python

Geben Sie im folgenden Codebeispiel den Wert Ihres Authentifizierungstokens an.

from google.cloud import tasks_v2beta3 as tasks

import requests


def send_task_to_http_queue(
    queue: tasks.Queue, body: str = "", token: str = "", headers: dict = {}
) -> int:
    """Send a task to an HTTP queue.
    Args:
        queue: The queue to delete.
        body: The body of the task.
        auth_token: An authorization token for the queue.
        headers: Headers to set on the task.
    Returns:
        The matching queue, or None if it does not exist.
    """

    # Use application default credentials if not supplied in a header
    if token:
        headers["Authorization"] = f"Bearer {token}"

    endpoint = f"https://cloudtasks.googleapis.com/v2beta3/{queue.name}/tasks:buffer"
    response = requests.post(endpoint, body, headers=headers)

    return response.status_code

curl

curl -X HTTP_METHOD\
"https://cloudtasks.googleapis.com/v2/projects/PROJECT_ID/locations/LOCATION/queues/QUEUE_ID/tasks:buffer" \
    -H "Authorization: Bearer ACCESS_TOKEN"

Ersetzen Sie Folgendes:

  • HTTP_METHOD: Die HTTP-Methode für Ihre Anfrage, z. B. GET oder POST.
  • PROJECT_ID: ID Ihres Google Cloud-Projekts. Sie können sie abrufen, indem Sie Folgendes in Ihrem Terminal ausführen:
    gcloud config get-value project
  • LOCATION: Der Speicherort deiner Warteschlange.
  • QUEUE_ID: Die ID der Warteschlange.
  • ACCESS_TOKEN: Ihr Zugriffstoken. Sie können sie abrufen, indem Sie Folgendes in Ihrem Terminal ausführen:
  • gcloud auth application-default login
  • gcloud auth application-default print-access-token

Methode CreateTask

In den folgenden Beispielen wird die Methode CreateTask mit den Cloud Tasks-Clientbibliotheken verwendet, um eine Aufgabe zu erstellen, die auch das Erstellen eines Header-Tokens enthält. In den Beispielen werden ID-Tokens verwendet. Wenn Sie ein Zugriffstoken verwenden möchten, ersetzen Sie beim Erstellen der Anfrage den OIDC-Parameter durch den sprachbasierten OAuth-Parameter.

Python

from typing import Optional

from google.cloud import tasks_v2


def create_http_task_with_token(
    project: str,
    location: str,
    queue: str,
    url: str,
    payload: bytes,
    service_account_email: str,
    audience: Optional[str] = None,
) -> tasks_v2.Task:
    """Create an HTTP POST task with an OIDC token and an arbitrary payload.
    Args:
        project: The project ID where the queue is located.
        location: The location where the queue is located.
        queue: The ID of the queue to add the task to.
        url: The target URL of the task.
        payload: The payload to send.
        service_account_email: The service account to use for generating the OIDC token.
        audience: Audience to use when generating the OIDC token.
    Returns:
        The newly created task.
    """

    # Create a client.
    client = tasks_v2.CloudTasksClient()

    # Construct the request body.
    task = tasks_v2.Task(
        http_request=tasks_v2.HttpRequest(
            http_method=tasks_v2.HttpMethod.POST,
            url=url,
            oidc_token=tasks_v2.OidcToken(
                service_account_email=service_account_email,
                audience=audience,
            ),
            body=payload,
        ),
    )

    # Use the client to build and send the task.
    return client.create_task(
        tasks_v2.CreateTaskRequest(
            parent=client.queue_path(project, location, queue),
            task=task,
        )
    )

Beachten Sie die Datei requirements.txt:

google-cloud-tasks==2.13.1

Java

import com.google.cloud.tasks.v2.CloudTasksClient;
import com.google.cloud.tasks.v2.HttpMethod;
import com.google.cloud.tasks.v2.HttpRequest;
import com.google.cloud.tasks.v2.OidcToken;
import com.google.cloud.tasks.v2.QueueName;
import com.google.cloud.tasks.v2.Task;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.charset.Charset;

public class CreateHttpTaskWithToken {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String locationId = "us-central1";
    String queueId = "my-queue";
    String serviceAccountEmail =
        "java-docs-samples-testing@java-docs-samples-testing.iam.gserviceaccount.com";
    createTask(projectId, locationId, queueId, serviceAccountEmail);
  }

  // Create a task with a HTTP target and authorization token using the Cloud Tasks client.
  public static void createTask(
      String projectId, String locationId, String queueId, String serviceAccountEmail)
      throws IOException {

    // Instantiates a client.
    try (CloudTasksClient client = CloudTasksClient.create()) {
      String url =
          "https://example.com/taskhandler"; // The full url path that the request will be sent to
      String payload = "Hello, World!"; // The task HTTP request body

      // Construct the fully qualified queue name.
      String queuePath = QueueName.of(projectId, locationId, queueId).toString();

      // Add your service account email to construct the OIDC token.
      // in order to add an authentication header to the request.
      OidcToken.Builder oidcTokenBuilder =
          OidcToken.newBuilder().setServiceAccountEmail(serviceAccountEmail);

      // Construct the task body.
      Task.Builder taskBuilder =
          Task.newBuilder()
              .setHttpRequest(
                  HttpRequest.newBuilder()
                      .setBody(ByteString.copyFrom(payload, Charset.defaultCharset()))
                      .setHttpMethod(HttpMethod.POST)
                      .setUrl(url)
                      .setOidcToken(oidcTokenBuilder)
                      .build());

      // Send create task request.
      Task task = client.createTask(queuePath, taskBuilder.build());
      System.out.println("Task created: " + task.getName());
    }
  }
}

Beachten Sie die Datei pom.xml:

<?xml version='1.0' encoding='UTF-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.tasks</groupId>
  <artifactId>cloudtasks-snippets</artifactId>
  <packaging>jar</packaging>
  <name>Google Cloud Tasks Snippets</name>

  <!--
    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>


  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>libraries-bom</artifactId>
        <version>26.32.0</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-tasks</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.truth</groupId>
      <artifactId>truth</artifactId>
      <version>1.4.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Einfach loslegen (Go)

import (
	"context"
	"fmt"

	cloudtasks "cloud.google.com/go/cloudtasks/apiv2"
	taskspb "cloud.google.com/go/cloudtasks/apiv2/cloudtaskspb"
)

// createHTTPTaskWithToken constructs a task with a authorization token
// and HTTP target then adds it to a Queue.
func createHTTPTaskWithToken(projectID, locationID, queueID, url, email, message string) (*taskspb.Task, error) {
	// Create a new Cloud Tasks client instance.
	// See https://godoc.org/cloud.google.com/go/cloudtasks/apiv2
	ctx := context.Background()
	client, err := cloudtasks.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	// Build the Task queue path.
	queuePath := fmt.Sprintf("projects/%s/locations/%s/queues/%s", projectID, locationID, queueID)

	// Build the Task payload.
	// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#CreateTaskRequest
	req := &taskspb.CreateTaskRequest{
		Parent: queuePath,
		Task: &taskspb.Task{
			// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#HttpRequest
			MessageType: &taskspb.Task_HttpRequest{
				HttpRequest: &taskspb.HttpRequest{
					HttpMethod: taskspb.HttpMethod_POST,
					Url:        url,
					AuthorizationHeader: &taskspb.HttpRequest_OidcToken{
						OidcToken: &taskspb.OidcToken{
							ServiceAccountEmail: email,
						},
					},
				},
			},
		},
	}

	// Add a payload message if one is present.
	req.Task.GetHttpRequest().Body = []byte(message)

	createdTask, err := client.CreateTask(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("cloudtasks.CreateTask: %w", err)
	}

	return createdTask, nil
}

Node.js

// Imports the Google Cloud Tasks library.
const {CloudTasksClient} = require('@google-cloud/tasks');

// Instantiates a client.
const client = new CloudTasksClient();

async function createHttpTaskWithToken() {
  // TODO(developer): Uncomment these lines and replace with your values.
  // const project = 'my-project-id';
  // const queue = 'my-queue';
  // const location = 'us-central1';
  // const url = 'https://example.com/taskhandler';
  // const serviceAccountEmail = 'client@<project-id>.iam.gserviceaccount.com';
  // const payload = 'Hello, World!';

  // Construct the fully qualified queue name.
  const parent = client.queuePath(project, location, queue);

  const task = {
    httpRequest: {
      headers: {
        'Content-Type': 'text/plain', // Set content type to ensure compatibility your application's request parsing
      },
      httpMethod: 'POST',
      url,
      oidcToken: {
        serviceAccountEmail,
      },
    },
  };

  if (payload) {
    task.httpRequest.body = Buffer.from(payload).toString('base64');
  }

  console.log('Sending task:');
  console.log(task);
  // Send create task request.
  const request = {parent: parent, task: task};
  const [response] = await client.createTask(request);
  const name = response.name;
  console.log(`Created task ${name}`);
}
createHttpTaskWithToken();

Beachten Sie die Datei package.json:

{
  "name": "appengine-cloudtasks",
  "description": "Google App Engine Cloud Tasks example.",
  "license": "Apache-2.0",
  "author": "Google Inc.",
  "private": true,
  "engines": {
    "node": ">=16.0.0"
  },
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "c8 mocha -p -j 2 --timeout 30000",
    "start": "node server.js"
  },
  "dependencies": {
    "@google-cloud/tasks": "^4.0.0",
    "express": "^4.16.3"
  },
  "devDependencies": {
    "c8": "^8.0.0",
    "chai": "^4.2.0",
    "mocha": "^10.0.0",
    "uuid": "^9.0.0"
  }
}

Eigene HTTP-Zielaufgaben-Handler bereitstellen

HTTP Target-Aufgaben-Handler sind den App Engine-Aufgaben-Handlern mit den folgenden Ausnahmen sehr ähnlich:

  • Zeitüberschreitungen: Für alle HTTP-Ziel-Aufgaben-Handler beträgt das Standardzeitlimit 10 Minuten, maximal 30 Minuten.
  • Authentifizierungslogik: Wenn Sie Ihren eigenen Code in den Zieldienst schreiben, um das Token zu validieren, sollten Sie ein ID-Token verwenden. Weitere Informationen dazu finden Sie unter OpenID Connect im Abschnitt Validating an ID token.
  • Headers: Eine HTTP-Zielanfrage enthält Header, die von der Warteschlange festgelegt werden und aufgabenspezifische Informationen enthalten, die der Handler verwenden kann. Diese ähneln den in App Engine-Aufgabenanfragen festgelegten Headern, sind jedoch nicht mit diesen identisch. Diese Header enthalten nurnur Informationen. Sie sollten nicht als Identitätsquellen verwendet werden.

    Wenn diese Header in einer externen Nutzeranfrage an Ihre Anwendung vorhanden waren, werden sie durch die internen ersetzt. Die einzige Ausnahme dabei sind Anfragen von angemeldeten Administratoren der Anwendung, die Header für Testzwecke festlegen dürfen.

    HTTP-Zielanfragen enthalten immer die folgenden Header:

    Header Beschreibung
    X-CloudTasks-QueueName Der Name der Warteschlange.
    X-CloudTasks-TaskName Der "kurze" Name der Aufgabe oder, wenn bei der Erstellung kein Name festgelegt wurde, eine vom System generierte eindeutige ID. Dies ist der my-task-id-Wert im vollständigen Aufgabennamen, also task_name = projects/my-project-id/locations/my-location/queues/my-queue-id/tasks/my-task-id.
    X-CloudTasks-TaskRetryCount Die Anzahl der Ausführungsversuche für diese Aufgabe. Für den ersten Versuch lautet dieser Wert 0. Diese Zahl umfasst Versuche, bei denen die Aufgabe aufgrund von 5XX-Fehlercodes fehlgeschlagen ist und die Ausführungsphase nicht erreicht wurde.
    X-CloudTasks-TaskExecutionCount Die Gesamtzahl der Antworten, die die Aufgabe vom Handler erhalten hat. Da Cloud Tasks eine Aufgabe löscht, sobald eine erfolgreiche Antwort empfangen wurde, sind alle vorherigen Handler-Antworten fehlgeschlagen. Diese Zahl umfasst keine Fehler aufgrund von 5XX-Fehlercodes.
    X-CloudTasks-TaskETA Die geplante Zeit für eine Aufgabe, angegeben in Sekunden seit dem 1. Januar 1970.

    Außerdem können Anfragen von Cloud Tasks die folgenden Header enthalten:

    Header Beschreibung
    X-CloudTasks-TaskPreviousResponse Der HTTP-Antwortcode aus der vorangegangenen Wiederholung.
    X-CloudTasks-TaskRetryReason Der Grund für die Wiederholung der Aufgabe.

Cloud Tasks-Dienst-Agent-Rolle manuell zu Ihrem Cloud Tasks-Dienstkonto hinzufügen

Dies ist nur erforderlich, wenn Sie die Cloud Tasks API vor dem 19. März 2019 aktiviert haben.

Console verwenden

  1. Suchen Sie auf der Seite mit den Google Cloud-Projekteinstellungen nach der Projektnummer Ihres Projekts.
  2. Notieren Sie die Nummer.
  3. Öffnen Sie die Seite der IAM-Admin-Konsole.
  4. Klicken Sie auf Zugriff erlauben. Der Bildschirm Zugriff gewähren wird geöffnet.
  5. Fügen Sie im Bereich Hauptkonten hinzufügen eine E-Mail-Adresse im folgenden Format hinzu:

     service-PROJECT_NUMBER@gcp-sa-cloudtasks.iam.gserviceaccount.com
     

    Ersetzen Sie PROJECT_NUMBER durch die Projektnummer von oben.

  6. Wählen Sie im Abschnitt Rollen zuweisen den Cloud Tasks-Dienst-Agent aus.

  7. Klicken Sie auf Speichern.

gcloud verwenden

  1. Ermitteln Sie Ihre Projektnummer:

        gcloud projects describe PROJECT_ID --format='table(projectNumber)'
        

    Ersetzen Sie PROJECT_ID durch Ihre Projekt-ID.

  2. Notieren Sie die Nummer.

  3. Weisen Sie dem Cloud Tasks-Dienstkonto die Rolle Cloud Tasks Service Agent mit der Projektnummer zu, die Sie kopiert haben:

        gcloud projects add-iam-policy-binding PROJECT_ID --member serviceAccount:service-PROJECT_NUMBER@gcp-sa-cloudtasks.iam.gserviceaccount.com --role roles/cloudtasks.serviceAgent
    

    Ersetzen Sie PROJECT_ID durch Ihre Projekt-ID und PROJECT_NUMBER durch die Projektnummer von oben.

Erweiterte Konfiguration

Es gibt eine Reihe von Attributen, die Sie in Ihrer Aufgabe konfigurieren können. Eine vollständige Liste finden Sie in der Ressourcendefinition der Aufgabe.

Beispiele für Attribute, die Sie anpassen können:

  • Benennung:Wenn Sie einen Namen für die Aufgabe angeben, kann Cloud Tasks diesen Namen verwenden, um die Deduplizierung von Aufgaben sicherzustellen. Die hierfür erforderliche Verarbeitung kann jedoch die Latenz erhöhen.
  • Planung:Sie können eine Aufgabe für einen späteren Zeitpunkt planen. Nur unterstützt für CreateTask (nicht unterstützt für BufferTask)
  • Wiederholungskonfiguration: Konfigurieren Sie das Wiederholungsverhalten für eine Aufgabe, wenn die Aufgabe fehlschlägt. Nur unterstützt für CreateTask (nicht unterstützt für BufferTask)

Nächste Schritte