Crea attività di destinazione HTTP

I gestori di Cloud Tasks possono essere eseguiti su qualsiasi endpoint HTTP con un IP esterno come GKE, Compute Engine o anche un server web on-premise. Il tuo eseguire attività su qualsiasi di questi servizi in un ambiente moda.

Questa pagina mostra come creare in modo programmatico attività di destinazione HTTP di base e inserirli nella Coda di Cloud Tasks.

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

  • Metodo BufferTask: utilizza questo metodo se la coda è impostata su del buffer 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 BufferTask.

  • Metodo CreateTask: è più complesso. Devi di creare in modo esplicito un oggetto attività. Utilizza questo metodo se le attività in coda configurazioni di routing diverse. In questo caso, specifichi il routing a livello di attività e non può utilizzare il routing a livello di coda. Questo approccio utilizza 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 che usi si chiama BufferTask.

Limitazioni

Il metodo BufferTask è soggetto alle seguenti limitazioni:

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

  • 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à. Dal giorno non c'è posto per aggiungere informazioni di routing quando crei un'attività in questo modo, deve utilizzare il routing a livello di coda (altrimenti l'attività non ha informazioni di routing). 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

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

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 Metodo BufferTask che utilizza 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, per esempio GET o POST.
  • PROJECT_ID: l'ID del tuo progetto Google Cloud. Puoi ottenerlo eseguendo il comando seguente 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à. Utilizzi il metodo CreateTask.

Quando crei un'attività utilizzando il metodo CreateTask, crei e modifichi esplicitamente per definire l'oggetto dell'attività. Devi specificare il servizio e il gestore del processo l'attività.

Se vuoi, puoi passare dati specifici dell'attività al gestore. Puoi anche perfeziona il di configurazione per l'attività, ad esempio pianificare un'ora futura in cui deve essere eseguita o la limitazione del numero di volte in cui vuoi che l'attività venga ritentata se non riesce (vedi Configurazione avanzata).

Gli esempi seguenti chiamano il metodo CreateTask per creare un'attività utilizzando il metodo 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"
    }
}

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
}

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 concedere l'accesso ruoli appropriati. Queste istruzioni riguardano la creazione di un nuovo account di servizio in particolare per questa funzione. L'account di servizio nuovo o esistente utilizzato per l'autenticazione di Cloud Tasks deve trovarsi nello stesso progetto del tuo 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 crea un nome di account email correlato per l'account. Ecco come fare riferimento all'account. Puoi anche aggiungere una descrizione di cos'è l'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 consente all'account di servizio di autorizzare la coda a creare token su usando le credenziali dell'account di servizio.

  8. Se il tuo gestore fa parte di Google Cloud, concedi l'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. Per ad esempio per accedere a un gestore su Cloud Run richiede 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 proprio con Ruolo Cloud Tasks Service Agent concesso. In questo modo può generare un'intestazione token basati sulle credenziali associate a Cloud Tasks l'account di servizio per l'autenticazione con la destinazione del gestore. La L'account di servizio Cloud Tasks a cui viene concesso questo ruolo viene automaticamente vengono create al momento dell'abilitazione dell'API Cloud Tasks, a meno che non l'hai abilitata in precedenza al 19 marzo 2019, nel qual caso dovrai aggiungere il ruolo manualmente.

Utilizzo di attività di destinazione HTTP con token di autenticazione

Per l'autenticazione tra Cloud Tasks e una destinazione HTTP che richiede tale autenticazione, Cloud Tasks crea un token di intestazione. Questo token si basa sulle credenziali nel Account di servizio Cloud Tasks Enqueuer, identificato dal relativo indirizzo email. La l'account di servizio usato per l'autenticazione deve far parte dello stesso nel progetto in cui si trova la coda di Cloud Tasks. La richiesta, con di intestazione, viene inviato dalla coda al gestore tramite HTTPS. Puoi utilizzare uno dei seguenti metodi: 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 è per 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à. A configurare l'autenticazione a livello di coda, consulta Crea code di Cloud Tasks. Se l'autenticazione è configurata a livello di coda, questa configurazione sostituisce configurazione a livello di attività. Per configurare l'autenticazione a livello di attività, specifica uno dei seguenti Token ID (OIDC) o un token di accesso (OAuth) nell'attività per trovare le regole.

Metodo BufferTask

Gli esempi seguenti utilizzano le credenziali predefinite dell'applicazione per l'autenticazione quando utilizzando 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, per esempio GET o POST.
  • PROJECT_ID: l'ID del tuo progetto Google Cloud. Puoi ottenerlo eseguendo il comando seguente 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 trovarla esegui questo comando nel tuo terminale:
  • gcloud auth application-default login
  • gcloud auth application-default print-access-token

Metodo CreateTask

Nei seguenti esempi viene utilizzato il metodo CreateTask con il parametro tramite le librerie client di Cloud Tasks per creare un'attività include 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 linguaggio appropriato Parametro OAuth per la 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>

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
}

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 Gestori di attività di 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 nella casella di destinazione per convalidare il token, devi utilizzare un token ID. Per ulteriori informazioni sulle sue implicazioni, consulta OpenID Connect, in particolare Convalida di un token ID.
  • Intestazioni: una richiesta di destinazione HTTP ha intestazioni impostate dalla coda, che contengono e informazioni specifiche per l'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 di identità.

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

    Le richieste di destinazione HTTP contengono sempre le seguenti intestazioni:

    Intestazione Descrizione
    X-CloudTasks-QueueName Il nome della coda.
    X-CloudTasks-TaskName Lo "Short" nome 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:

    Intestazione 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 tuo progetto in 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 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, consulta l'attività definizione delle risorse.

Esempi di attributi che puoi personalizzare:

  • Denominazione: se hai scelto di specificare un nome per il attività, Cloud Tasks può utilizzare questo nome per garantire la deduplicazione delle attività, anche se l'elaborazione necessaria a questo scopo può aggiungere una maggiore latenza.
  • Programmazione:puoi programmare un'attività in un momento futuro. Supportate solo per CreateTask (non supportato per BufferTask)
  • Configurazione dei nuovi tentativi:configura il comportamento dei nuovi tentativi per un'attività se questa non riesce. Supportata solo per CreateTask (non supportata per BufferTask)

Passaggi successivi