亚马逊 MWS - 请求受限

Amazon MWS - Request Throttled

阅读节流文档 https://docs.developer.amazonservices.com/en_US/products/Products_Throttling.html and https://docs.developer.amazonservices.com/en_US/dev_guide/DG_Throttling.html 后,我开始尊重 quotaRemainingquotaResetsAt 响应 headers,这样我就不会超出引用限制。但是,每当我快速连续发出几个请求时,都会出现以下异常。

该文档没有提及任何有关突发限制的内容。它谈到最大请求配额,但我不知道这如何适用于我的情况。我正在调用 ListMatchingProducts api

Caused by: com.amazonservices.mws.client.MwsException: Request is throttled
    at com.amazonservices.mws.client.MwsAQCall.invoke(MwsAQCall.java:312)
    at com.amazonservices.mws.client.MwsConnection.call(MwsConnection.java:422)
    ... 19 more

我想我明白了。 ListMatchingProducts 提到最大请求配额是 20。实际上这意味着您可以快速连续触发最多 20 个请求,但之后您必须等到恢复率 "replenishes" 您的请求 "credits"(即在我的情况下每 5 秒 1 个请求)。

此恢复率将(每 5 秒)开始,然后重新填充配额,最多 20 个请求。以下代码对我有用...

class Client {
  private final int maxRequestQuota = 19
  private Semaphore maximumRequestQuotaSemaphore = new Semaphore(maxRequestQuota)
  private volatile boolean done = false

  Client() {
    new EveryFiveSecondRefiller().start()
  }

  ListMatchingProductsResponse fetch(String searchString) {
    maximumRequestQuotaSemaphore.acquire()
    // .....
  }

  class EveryFiveSecondRefiller extends Thread {
    @Override
    void run() {
      while (!done()) {
        int availablePermits = maximumRequestQuotaSemaphore.availablePermits()
        if (availablePermits == maxRequestQuota) {
          log.debug("Max permits reached. Waiting for 5 seconds")
          sleep(5000)
          continue
        }
        log.debug("Releasing a single permit. Current available permits are $availablePermits")
        maximumRequestQuotaSemaphore.release()
        sleep(5000)
      }
    }

    boolean done() {
      done
    }
  }

  void close() {
    done = true
  }
}