Crea attività di destinazione HTTP

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

Questa pagina mostra come creare in modo programmatico attività di destinazione HTTP di base e inserirle nelle code di Cloud Tasks.

Per le attività con destinazioni HTTP (anziché i target espliciti di App Engine, che sono meno comuni), esistono due modi per creare attività:

  • Metodo BufferTask: utilizza questo metodo se la coda è configurata per eseguire il buffer delle attività davanti a 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à in coda hanno configurazioni di routing diverse. In questo caso, devi specificare 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à mediante l'invio di una richiesta HTTP. Il metodo utilizzato è chiamato 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 routing in questo modo quando si crea un'attività, è necessario utilizzare il routing a livello di coda (in caso contrario l'attività non ha informazioni di routing). Se la coda non utilizza già il routing a livello di coda, vedi Configurare il routing a livello di coda per le attività HTTP.

Chiama il metodo BufferTask

I seguenti esempi mostrano come creare un'attività inviando una richiesta POST HTTP all'endpoint buffer dell'API Cloud Tasks.

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

Il seguente snippet di codice mostra un esempio di creazione di attività utilizzando 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 tua richiesta, ad esempio GET o POST.
  • PROJECT_ID: l'ID del tuo progetto Google Cloud. Puoi ottenerlo eseguendo questo comando nel terminale:
    gcloud config get-value project
  • LOCATION: la posizione della coda.
  • QUEUE_ID: l'ID della coda.

Creazione di attività avanzata (metodo CreateTask)

Questa sezione illustra la creazione di un'attività costruendo l'oggetto dell'attività. Usi il metodo CreateTask.

Quando crei un'attività utilizzando il metodo CreateTask, crei e definisci in modo esplicito l'oggetto attività. Devi specificare il servizio e il gestore che elaborano l'attività.

Se vuoi, puoi passare dati specifici dell'attività al gestore. Puoi anche ottimizzare la configurazione per l'attività, ad esempio pianificare un'ora futura in cui eseguire l'attività o limitare il numero di volte in cui vuoi che l'attività venga ritentata in caso di esito negativo (consulta Configurazione avanzata).

Gli esempi seguenti chiamano il metodo CreateTask per creare un'attività utilizzando le librerie client di 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;
    }
}

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

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>

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

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

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": "^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

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

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

Se disponi di un account di servizio attuale che vuoi utilizzare, puoi farlo. Devi solo assegnare i ruoli appropriati. Queste istruzioni illustrano la creazione di un nuovo account di servizio specifico per questa funzione. L'account di servizio nuovo o esistente utilizzato per l'autenticazione di Cloud Tasks deve trovarsi nello stesso progetto delle code di 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 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 In coda di Cloud Tasks. 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 tuo gestore fa parte di Google Cloud, concedi all'account di servizio il ruolo associato all'accesso al servizio su cui è in esecuzione il gestore. Ogni servizio all'interno di Google Cloud richiede un ruolo diverso. Ad esempio, per accedere a un gestore su Cloud Run è necessario il ruolo Invoker di Cloud Run e così via. Puoi utilizzare l'account di servizio che hai appena creato o qualsiasi altro account di servizio nel tuo progetto.

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

Cloud Tasks deve disporre di un 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 l'autenticazione con la destinazione del gestore. L'account di servizio Cloud Tasks a cui viene concesso questo ruolo viene creato automaticamente al momento dell'abilitazione dell'API Cloud Tasks, a meno che non sia stata abilitata prima del 19 marzo 2019. In questo caso, dovrai aggiungere il ruolo manualmente.

Utilizzo di attività di destinazione HTTP con token di autenticazione

Per eseguire l'autenticazione tra Cloud Tasks e un gestore di destinazione HTTP che richiede questa autenticazione, Cloud Tasks crea un token di intestazione. Questo token si basa sulle credenziali nell'account di servizio Cloud Tasks Enqueuer, identificato in base all'indirizzo email. L'account di servizio utilizzato per l'autenticazione deve far parte dello stesso progetto in cui si trova la coda di Cloud Tasks. La richiesta, con il token di intestazione, viene inviata dalla coda al gestore tramite HTTPS. Puoi utilizzare un token ID o un token di accesso. I token ID in genere devono essere utilizzati per qualsiasi gestore in esecuzione su Google Cloud, ad esempio su Cloud Functions o Cloud Run. L'eccezione principale sono le API di Google ospitate su *.googleapis.com: queste API prevedono un token di accesso.

Puoi configurare l'autenticazione a livello di coda o di attività. Per configurare l'autenticazione a livello di coda, vedi Creare code di Cloud Tasks. Se l'autenticazione è configurata a livello di coda, questa configurazione sostituisce la 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 seguenti utilizzano le credenziali predefinite dell'applicazione per l'autenticazione quando si utilizza il metodo BufferTask per creare un'attività.

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 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"

Sostituisci quanto segue:

  • HTTP_METHOD: il metodo HTTP per la tua richiesta, ad esempio GET o POST.
  • PROJECT_ID: l'ID del tuo progetto Google Cloud. Puoi ottenerlo eseguendo questo 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 ottenerlo eseguendo questo comando nel terminale:
  • gcloud auth application-default login
  • gcloud auth application-default print-access-token

Metodo CreateTask

I seguenti esempi utilizzano il metodo CreateTask con le librerie client di Cloud Tasks per creare un'attività che include anche la creazione di un token di 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 nella creazione della richiesta.

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

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>

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

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": "^4.0.0",
    "express": "^4.16.3"
  },
  "devDependencies": {
    "c8": "^8.0.0",
    "chai": "^4.2.0",
    "mocha": "^10.0.0",
    "uuid": "^9.0.0"
  }
}

Fornire i tuoi gestori di attività di destinazione HTTP

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

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

    Se queste intestazioni erano presenti nella richiesta di un utente esterno alla tua app, vengono sostituite da quelle interne. L'unica eccezione riguarda le richieste da parte di amministratori dell'applicazione che hanno eseguito l'accesso, a cui è consentito impostare intestazioni a scopo di test.

    Le richieste di destinazione 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. Questo è il valore my-task-id nel nome dell'attività completa, ad esempio nome_attività = projects/my-project-id/locations/my-location/queues/my-queue-id/tasks/my-task-id.
    X-CloudTasks-TaskRetryCount Il numero di nuovi tentativi 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 dal gestore. Poiché Cloud Tasks elimina l'attività dopo aver ricevuto una risposta positiva, tutte le risposte precedenti del gestore sono risultate errori. Questo numero non include errori dovuti a codici di errore 5XX.
    X-CloudTasks-TaskETA L'ora di pianificazione dell'attività, specificata in secondi dal 1° gennaio 1970.

    Inoltre, le richieste da 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 hai eseguito di nuovo l'attività.

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

Questa operazione è necessaria solo se hai abilitato l'API Cloud Tasks prima del 19 marzo 2019.

Utilizzo della console

  1. Trova il numero del progetto nella pagina Impostazioni progetto di Google Cloud.
  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 formato:

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

    Sostituisci PROJECT_NUMBER con il numero del tuo progetto qui sopra.

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

  7. Fai clic su Salva.

Utilizzo di gcloud

  1. Trova il numero del tuo 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 PROJECT_ID con il tuo ID progetto e PROJECT_NUMBER con il numero del tuo progetto in alto.

Configurazione avanzata

Nell'attività puoi configurare una serie di attributi. Per un elenco completo, consulta la definizione delle risorse dell'attività.

Esempi di attributi che puoi personalizzare:

  • Denominazione: se scegli di specificare un nome per l'attività, Cloud Tasks può utilizzare questo nome per garantire la deduplicazione delle attività, sebbene l'elaborazione necessaria a tal fine possa aumentare la latenza.
  • Programmazione:puoi programmare un'attività in un momento futuro. Supportata solo per CreateTask (non supportata per BufferTask)
  • Configurazione dei nuovi tentativi: configura il comportamento dei nuovi tentativi per un'attività se l'attività non riesce. Supportata solo per CreateTask (non supportata per BufferTask)

Passaggi successivi