Creare attività target HTTP

I gestori di Cloud Tasks possono essere eseguiti su qualsiasi endpoint HTTP con un indirizzo IP esterno, ad esempio GKE, Compute Engine o anche un server web on-premise. Le tue attività possono essere eseguite su uno di questi servizi in modo affidabile e configurabile.

Questa pagina mostra come creare ed eseguire programmaticamente attività target HTTP di base e inserirle nelle code Cloud Tasks.

Per le attività con target HTTP (a differenza dei target App Engine espliciti, meno comuni), esistono due modi per creare attività:

  • Metodo BufferTask: utilizza questo metodo se la coda è configurata per mettere in coda le attività prima di un servizio. La coda deve avere il routing a livello di coda. Per la maggior parte dei casi d'uso, questo è l'approccio migliore. Questo approccio utilizza il metodo BufferTask.

  • Metodo CreateTask: più complesso. Devi creare esplicitamente un oggetto attività. Utilizza questo metodo se le attività nella coda hanno configurazioni di routing diverse. In questo caso, specifichi il routing a livello di attività e non puoi utilizzare il routing a livello di coda. Questo approccio utilizza il metodo CreateTask.

Creazione di attività di base (metodo BufferTask)

Questa sezione illustra la creazione di un'attività inviando una richiesta HTTP. Il metodo che utilizzi si chiama BufferTask.

Limitazioni

Il metodo BufferTask è soggetto alle seguenti limitazioni:

  • Librerie client:il metodo BufferTask non è supportato nelle librerie client.

  • API RPC: il metodo BufferTask non è supportato nell'API RPC.

  • Routing a livello di attività:questo metodo non supporta il routing a livello di attività. Poiché non è possibile aggiungere informazioni di instradamento durante la creazione di un'attività in questo modo, devi utilizzare l'instradamento a livello di coda (in caso contrario l'attività non avrà informazioni di instradamento). Se la coda non utilizza già il routing a livello di coda, consulta Configurare il routing a livello di coda per le attività HTTP.

Chiama il metodo BufferTask

Gli esempi riportati di seguito mostrano come creare un'attività inviando una richiesta POST HTTP all'endpoint buffer dell'API Cloud Tasks.

curl

Il seguente snippet di codice mostra un esempio di creazione di attività con il metodo BufferTask utilizzando curl:

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

Sostituisci quanto segue:

  • HTTP_METHOD: il metodo HTTP per la richiesta, ad esempio GET o POST.
  • PROJECT_ID: l'ID del tuo Google Cloud progetto. Puoi ottenere questo valore eseguendo il seguente comando nel terminale:
    gcloud config get-value project
  • LOCATION: la posizione della coda.
  • QUEUE_ID: l'ID della coda.

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 send task to.
        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 doesn't 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

Creazione di attività avanzata (metodo CreateTask)

Questa sezione illustra la creazione di un'attività mediante la costruzione dell'oggetto task. Utilizzi il metodo CreateTask.

Quando crei un'attività utilizzando il metodo CreateTask, crei e definisci esplicitamente l'oggetto attività. Devi specificare il servizio e l'handler che elaborano la task.

Se vuoi, puoi passare al gestore i dati specifici dell'attività. Puoi anche perfezionare la configurazione dell'attività, ad esempio pianificare un momento futuro in cui deve essere eseguita o limitare il numero di volte in cui vuoi che venga riprovato se non va a buon fine (consulta Configurazione avanzata).

Gli esempi riportati di seguito chiamano il metodo CreateTask per creare un'attività utilizzando le librerie client Cloud Tasks.

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;
    }
}

Vai


// 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
}

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());
    }
  }
}

Prendi nota del file 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>

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();

Prendi nota del file 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": "^5.0.0",
    "express": "^4.16.3"
  },
  "devDependencies": {
    "c8": "^10.0.0",
    "chai": "^4.5.0",
    "mocha": "^10.0.0",
    "uuid": "^10.0.0"
  }
}

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());

Prendi nota del file composer.json:

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

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,
        )
    )

Prendi nota del file requirements.txt:

google-cloud-tasks==2.13.1

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

Configurazione degli account di servizio per l'autenticazione dei gestori target HTTP

Cloud Tasks può chiamare gestori target HTTP che richiedono l'autenticazione se disponi di un service account con le credenziali appropriate per accedere al gestore.

Se hai un account di servizio attuale che vuoi utilizzare, puoi farlo. Basta assegnare i ruoli appropriati. Queste istruzioni riguardano la creazione di un nuovo account di servizio specificamente per questa funzione. L'account di servizio esistente o nuovo utilizzato per l'autenticazione di Cloud Tasks deve trovarsi nello stesso progetto delle code Cloud Tasks.

  1. Nella console Google Cloud, vai alla pagina Account di servizio.

    Vai ad Account di servizio

  2. Se necessario, seleziona il progetto appropriato.

  3. Fai clic su Crea account di servizio.

  4. Nella sezione Dettagli account di servizio, assegna un nome all'account. La console crea un nome dell'account email correlato per l'account. In questo modo puoi fare riferimento all'account. Puoi anche aggiungere una descrizione dell'account. Fai clic su Crea e continua.

  5. Nella sezione Concedi a questo account di servizio l'accesso al progetto, fai clic su Seleziona un ruolo. Cerca e seleziona Cloud Tasks Enqueuer. Questo ruolo concede all'account di servizio l'autorizzazione per aggiungere attività alla coda.

  6. Fai clic su + Aggiungi un altro ruolo.

  7. Fai clic su Seleziona un ruolo. Cerca e seleziona Utente account di servizio. Questo ruolo consente all'account di servizio di autorizzare la coda a creare token per suo conto utilizzando le credenziali dell'account di servizio.

  8. Se il gestore fa parte di Google Cloud, concedi all'account di servizio il ruolo associato all'accesso al servizio in cui è in esecuzione il gestore. Ogni servizio al suo interno Google Cloud richiede un ruolo diverso. Ad esempio, per accedere a un gestore su Cloud Run, concedi il ruolo Invoker di Cloud Run. Puoi utilizzare l'account di servizio appena creato o qualsiasi altro account di servizio nel progetto.

  9. Fai clic su Fine per completare la creazione dell'account di servizio.

Cloud Tasks stesso deve avere un proprio account di servizio a cui è stato concesso il ruolo Cloud Tasks Service Agent. In questo modo, può generare token di intestazione in base alle credenziali associate all'account di servizio Cloud Tasks per autenticarsi con il gestore target. L'account di servizio Cloud Tasks a cui è stato concesso questo ruolo viene creato automaticamente quando attivi l'API Cloud Tasks, a meno che non l'abbia attivato prima del 19 marzo 2019, nel qual caso devi aggiungere il ruolo manualmente.

Utilizzo di attività target HTTP con token di autenticazione

Per l'autenticazione tra Cloud Tasks e un gestore di target HTTP che richiede questa autenticazione, Cloud Tasks crea un token intestazione. Questo token si basa sulle credenziali nell'account di servizio Cloud Tasks Enqueuer, identificato dal relativo indirizzo email. Il service account utilizzato per l'autenticazione deve far parte dello stesso progetto in cui risiede la coda Cloud Tasks. La richiesta, con il token di intestazione, viene inviata dalla coda all'handler tramite HTTPS. Puoi utilizzare un token ID o un token di accesso. In genere, i token ID devono essere utilizzati per qualsiasi gestore in esecuzione su Google Cloud, ad esempio nelle funzioni Cloud Run o in Cloud Run. L'eccezione principale riguarda le API di Google ospitate su *.googleapis.com: queste API richiedono un token di accesso.

Puoi configurare l'autenticazione a livello di coda o di attività. Per configurare l'autenticazione a livello di coda, consulta Creare code Cloud Tasks. Se l'autenticazione è configurata a livello di coda, questa configurazione ha la precedenza sulla configurazione a livello di attività. Per configurare l'autenticazione a livello di attività, specifica un token ID (OIDC) o un token di accesso (OAuth) nell'attività stessa.

Metodo BufferTask

Gli esempi riportati di seguito utilizzano le credenziali predefinite dell'applicazione per l'autenticazione quando si utilizza il metodo BufferTask per creare un'attività.

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"

Sostituisci quanto segue:

  • HTTP_METHOD: il metodo HTTP per la richiesta, ad esempio GET o POST.
  • PROJECT_ID: l'ID del tuo Google Cloud progetto. Per farlo, esegui il seguente comando nel terminale:
    gcloud config get-value project
  • LOCATION: la posizione della coda.
  • QUEUE_ID: l'ID della coda.
  • ACCESS_TOKEN: il tuo token di accesso. Puoi ottenere questo valore eseguendo il seguente comando nel terminale:
  • gcloud auth application-default login
  • gcloud auth application-default print-access-token

Python

Nel seguente esempio di codice, fornisci il valore del token di autenticazione.

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 send task to.
        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 doesn't 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

Metodo CreateTask

Gli esempi riportati di seguito utilizzano il metodo CreateTask con le librerie client Cloud Tasks per creare un'attività che include anche la creazione di un token intestazione. Negli esempi vengono utilizzati token ID. Per utilizzare un token di accesso, sostituisci il parametro OIDC con il parametro OAuth appropriato per la lingua durante la creazione della richiesta.

Vai

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
}

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());
    }
  }
}

Prendi nota del file 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>

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();

Prendi nota del file 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": "^5.0.0",
    "express": "^4.16.3"
  },
  "devDependencies": {
    "c8": "^10.0.0",
    "chai": "^4.5.0",
    "mocha": "^10.0.0",
    "uuid": "^10.0.0"
  }
}

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,
        )
    )

Prendi nota del file requirements.txt:

google-cloud-tasks==2.13.1

Fornire i tuoi gestori delle attività target HTTP

I gestori delle attività di destinazione HTTP sono molto simili ai gestori delle attività App Engine, con le seguenti eccezioni:

  • Timeout: per tutti i gestori delle attività target HTTP, il timeout predefinito è di 10 minuti, con un massimo di 30 minuti.
  • Logica di autenticazione: se scrivi il tuo codice nel servizio di destinazione per convalidare il token, devi utilizzare un token ID. Per ulteriori informazioni su cosa comporta, consulta OpenID Connect, in particolare la pagina Convalida di un token ID.
  • Intestazioni: una richiesta di destinazione HTTP ha intestazioni impostate dalla coda, che contengono informazioni specifiche della task che il gestore può utilizzare. Sono simili, ma non identiche, alle intestazioni impostate sulle richieste di attività App Engine. Queste intestazioni forniscono solo informazioni. Non devono essere utilizzate come fonti di identità.

    Se queste intestazioni erano presenti in una richiesta di un utente esterno alla tua app, vengono sostituite da quelle interne. L'unica eccezione riguarda le richieste degli amministratori dell'applicazione che hanno eseguito l'accesso e che sono autorizzati a impostare le intestazioni a scopo di test.

    Le richieste target HTTP contengono sempre le seguenti intestazioni:

    Titolo Descrizione
    X-CloudTasks-QueueName Il nome della coda.
    X-CloudTasks-TaskName Il nome "breve" dell'attività o, se non è stato specificato alcun nome al momento della creazione, un ID univoco generato dal sistema. Si tratta del valore my-task-id nel nome completo dell'attività, ad esempio task_name = projects/my-project-id/locations/my-location/queues/my-queue-id/tasks/my-task-id.
    X-CloudTasks-TaskRetryCount Il numero di volte in cui è stato eseguito un nuovo tentativo per questa attività. Per il primo tentativo, questo valore è 0. Questo numero include i tentativi in cui l'attività non è riuscita a causa di codici di errore 5XX e non ha mai raggiunto la fase di esecuzione.
    X-CloudTasks-TaskExecutionCount Il numero totale di volte in cui l'attività ha ricevuto una risposta dall'handler. Poiché Cloud Tasks elimina l'attività dopo aver ricevuto una risposta positiva, tutte le risposte precedenti dell'handler sono state errori. Questo numero non include gli errori dovuti a codici di errore 5XX.
    X-CloudTasks-TaskETA L'ora pianificata dell'attività, specificata in secondi dal 1° gennaio 1970.

    Inoltre, le richieste di Cloud Tasks potrebbero contenere le seguenti intestazioni:

    Titolo Descrizione
    X-CloudTasks-TaskPreviousResponse Il codice di risposta HTTP del tentativo precedente.
    X-CloudTasks-TaskRetryReason Il motivo per cui riprovare a eseguire l'attività.

Aggiunta manuale del ruolo Agente di servizio Cloud Tasks all'account di servizio Cloud Tasks

Questo passaggio è necessario solo se hai attivato l'API Cloud Tasks prima del 19 marzo 2019.

Console

  1. Trova il numero del progetto nella Google Cloud pagina Impostazioni progetto.
  2. Copia il numero.
  3. Apri la pagina della Console di amministrazione IAM.
  4. Fai clic su Concedi accesso. Si apre la schermata Concedi l'accesso.
  5. Nella sezione Aggiungi entità, aggiungi un indirizzo email nel seguente formato:

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

    Sostituisci PROJECT_NUMBER con il numero del tuo Google Cloud progetto.

  6. Nella sezione Assegna i ruoli, cerca e seleziona Agente del servizio Cloud Tasks.

  7. Fai clic su Salva.

gcloud

  1. Trova il numero del progetto:

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

    Sostituisci PROJECT_ID con l'ID progetto.

  2. Copia il numero.

  3. Concedi all'account di servizio Cloud Tasks il ruolo Cloud Tasks Service Agent utilizzando il numero di progetto che hai copiato:

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

    Sostituisci quanto segue:

    • PROJECT_ID: il tuo Google Cloud ID progetto.
    • PROJECT_NUMBER: il Google Cloud numero del progetto.

Configurazione avanzata

Esistono diversi attributi che puoi configurare nell'attività. Per un elenco completo, consulta la definizione della risorsa dell'attività.

Esempi di attributi che puoi personalizzare:

  • Nomi:se hai scelto di specificare un nome per l'attività, Cloud Tasks può utilizzarlo per garantire la deduplica delle attività, anche se l'elaborazione necessaria per questo può aumentare la latenza.
  • Pianificazione:puoi pianificare un'attività per un momento successivo. Supportato solo per CreateTask (non supportato per BufferTask)
  • Configurazione nuovi tentativi:configura il comportamento di nuovo tentativo per un'attività se non va a buon fine. Supportato solo per CreateTask (non supportato per BufferTask)

Passaggi successivi