Gmail Api 不断发送 429,但远低于使用配额

问题描述 投票:0回答:1

我将用户帐户的 Gmail 消息与 Ruby on Rails 应用程序同步。我使用 google-api-ruby-client,更具体地说,是 gem“google-apis-gmail_v1”。

我经常收到 429 错误,这些错误被捕获,导致所有批处理请求重新启动,从而产生大量无用的请求。

代码是什么:

首先:它通过“messages.list”调用列出 Gmail 邮件的“ids”(成本:每次调用 5 个配额单位)

gmail = gmail_service(employee)
gmail.fetch_all(items: :messages) do |token|
    gmail.list_user_messages(
                    'me',
                    page_token: token,
                    quota_user: employee.id,
                    include_spam_trash: false
                )
end.each_slice(25) do |ids|
    sleep(0.5) # THROTTLING MANAGEMENT
    fetch_messages_from_ids(employee, ids.map(&:id))
    sleep(0.5)

对于每 25 条消息,它通过“message.get”调用获取消息(成本:每条消息 5 单位配额 = 每批 125 单位配额)

def fetch_messages_from_ids(employee, messages_ids)
    gmail.batch do |gmail|
        messages_ids.each do |id|
            gmail.get_user_message(
                'me',
                id,
                quota_user: employee.id,
                format: 'metadata',
                fields: 'id, history_id, label_ids, payload, size_estimate'
                ) do |result, err|
                    # Manage API answers
            end
        end
    end
end

我经常(在员工同步期间多次)收到 429 错误。

我检查了 Gmail API 文档。

我的代码第二个消耗的最大配额单位:5(message.list)+ 25 * 5(批量中的25条message.get)= 130个单位,远低于Gmail API文档中解释的250个限制:https:// Developers.google.com/gmail/api/reference/quota

我尝试过的:

  • 减少到一批 25 个(而不是最初的 50 个)
  • 按照 Gmail 文档中的建议进行“批量”请求
  • 添加了两个“睡眠”以确保这些调用在一秒以上完成

指数退避似乎是批量请求中的一个问题:如果一个调用发回 429,则发送整批 25 个请求。这就是为什么我想找到一个比仅使用 gem 指数退避更好的解决方案。

ruby-on-rails gmail-api
1个回答
0
投票

问题是,当您尝试使用批处理时,它会同时发送所有请求,它们都同时到达服务器,这可能会给您带来配额运行问题,最好不要使用批处理,如果您将使用批量,一次仅发送大约五个。

© www.soinside.com 2019 - 2024. All rights reserved.