谷歌云功能对大量任务进行排队

Cha*_*ton 2 python google-cloud-platform google-cloud-functions google-cloud-scheduler google-cloud-tasks

我正在尝试使用云函数通过每天调用外部 API 一次来更新数据。

到目前为止我有:

  • 云计划设置为调用功能 1

  • 功能 1 - 循环项目并为每个项目创建一个任务

  • 任务 - 使用函数 1 提供的数据调用函数 2

  • 功能2 - 调用外部API来获取数据并更新我们的数据库

问题是每天有大约 2k 项需要更新,而云函数在执行此操作之前会超时,因此我将它们放入队列中。但即使将项目放入队列中,云功能也会花费太长时间,因此在添加所有项目之前就会超时。

有没有一种简单的方法可以一次将多个任务批量添加到队列中?

如果做不到这一点,有更好的解决方案吗?

全部用python编写

函数1的代码:

def refresh(request):
    for i in items:
        # Create a client.
        client = tasks_v2.CloudTasksClient()

        # TODO(developer): Uncomment these lines and replace with your values.
        project = 'my-project'
        queue = 'refresh-queue'
        location = 'europe-west2'
        name = i['name'].replace(' ','')
        url = f"https://europe-west2-my-project.cloudfunctions.net/endpoint?name={name}"

        # Construct the fully qualified queue name.
        parent = client.queue_path(project, location, queue)

        # Construct the request body.
        task = {
            "http_request": {  # Specify the type of request.
                "http_method": tasks_v2.HttpMethod.GET,
                "url": url,  # The full url path that the task will be sent to.
            }
        }
        

        # Use the client to build and send the task.
        response = client.create_task(request={"parent": parent, "task": task})
Run Code Online (Sandbox Code Playgroud)

Chr*_*s32 5

回答你的问题 \xe2\x80\x9c有没有一种简单的方法可以一次批量添加多个任务到队列中?\xe2\x80\x9d 根据公共文档的方法是实现双注入模式。

\n

为此,您将有一个新队列,您将在其中添加一个包含原始队列的多个任务的单个任务,然后在该队列的接收端,您将有一个服务来获取该任务的数据并创建第二个队列上的每个条目一个任务。

\n

此外,我建议您对冷队列使用500/50/5模式。这将有助于任务队列和云功能服务达到安全比率。

\n