【问题标题】:Sending a JSON payload to a Google Cloud Task将 JSON 负载发送到 Google Cloud Task
【发布时间】:2018-11-17 22:16:24
【问题描述】:

我可能遗漏了一些非常明显的东西,但在我正在从事的项目中,我必须从信息的 CSV 发送许多工作以异步处理,而 Google App Engine 目前的方式是通过他们的新(测试版) Cloud Tasks 机制。

它将接受负载作为任务的一部分,因此我将发送一个 JSON 数组,其中包含每个作业的相关数据...除了指示 "Content-Type: application/json" 标头的唯一方法是在创建任务对象期间.

我正在使用 Google 自己的 cloud-tasks 0.5.0 库。

这是我一直在尝试的,因为这似乎是大多数其他非 cURL HTTP POST 请求接受 Content-Type 标头的方式...

require_once 'vendor/autoload.php';

use Google\Cloud\Tasks\V2beta3\AppEngineHttpQueue;
use Google\Cloud\Tasks\V2beta3\CloudTasksClient;
use Google\Cloud\Tasks\V2beta3\Queue;
use Google\Cloud\Tasks\V2beta3\Task;

<<< ...lots of cruft omitted... >>>

        $json_payload = json_encode(
            array(
                "batch" => $operation_time,
                "order" => $csvln[0],
                "customer" => $csvln[1],
                "email" => $csvln[2],
                "salesperson" => $csvln[3]
            )
        );

        //Create each of the tasks in the queue
        $options = [
            'http' => [
                'header'  => "Content-type: application/json",
                'method'  => 'POST',
                'content' => $json_payload
            ]
        ];

        $task = new Task($options);

任何帮助将不胜感激!

【问题讨论】:

  • 你有没有得到这个工作?我在将参数传递给每个单独的任务时遇到了同样的问题,并且我发现关于如何发送 json 正文(相对于原始 base64 有效负载字符串)的信息非常少。我假设我可以将整个 json 主体编码为 base64 有效负载,然后在任务处理程序中解析它,但我认为有更好的方法
  • 我没有。相反,我推迟了一种策略,似乎谷歌可能会逐步淘汰这些新方法......推送任务。不过,这些都是蛋糕。
  • 我知道您找到了解决此问题的解决方法,对吗?你能分享你用来解决这个问题的文档吗?

标签: php google-app-engine google-cloud-platform php-5.5


【解决方案1】:

您可以使用来自Cloud Tasks PHP Client LibraryApp Engine HTTP Request 将带有预定义负载的任务加载到任务队列中。

定义任务后,您可以使用AppEngineHttpRequest 提供给您的setter 方法来构造带有任何所需标头的HTTP 对象。这也将允许分配有效负载。

下面是一个简单的 sn-p,展示了如何将带有有效负载的任务附加到默认队列:

use Google\Cloud\Tasks\V2beta3\AppEngineHttpRequest;
use Google\Cloud\Tasks\V2beta3\HttpMethod;
use Google\Cloud\Tasks\V2beta3\Task;

//Preparing the payload
$json_payload = json_encode(
    array(
        "batch"       => date("h:i:sa"),
        "order"       => "Payload-0000",
        "customer"    => "Payload-0001",
        "email"       => "Payload-0002",
        "salesperson" => "Payload-0003"
    )
);

//Create and configure the task   
$httpR=new AppEngineHttpRequest();
$httpR->setBody($json_payload);
$httpR->setHeaders(['Content-type'=>'application/json']);
$httpR->setHttpMethod(HttpMethod::POST);   
$httpR->setRelativeUri("/example_task_handler");

$task = new Task();
$task->setAppEngineHttpRequest($httpR);

还可以考虑更新您的库,因为当前版本是 v0.86.0,即使在创建任务对象之后,它也允许分配标头。

【讨论】:

  • @smoopins 嘿,我很高兴这对你有用。如果你愿意,你可以支持我的回答。
  • 点击按钮,但我仍然缺乏街头信誉来展示它。总有一天,我会在 StackOverflow 大佬眼中变得更好! ;)
  • @smoopins 感谢您的尝试。一切顺利。
猜你喜欢
  • 2020-02-04
  • 1970-01-01
  • 2018-07-31
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-25
相关资源
最近更新 更多