我在敲打一个api,如果您在五分钟的时间内将它打了250次以上,它将返回429,太多的请求和响应。计数每五分钟重置一次,所以我一直在这样处理:
try
{
return request.GetResponse();
}
catch (Exception e)
{
if (e.Message.Contains("429"))
{
System.Threading.Thread.Sleep(5 * 60 * 1000);
return request.GetResponse();
}
else
{
throw new Exception(e.Message);
}
}
这是处理这种情况的正确方法吗?
这里要考虑的一件事是,如果您开始超过限制,您正在使用的api可能会“惩罚”您。我认为最好是主动主动并限制您的api请求,这样您就永远不会收到429错误。
我们从我们正在使用的api开始在我们的应用程序上遇到了同样的事情(429个错误)。此特定api的限制是每60秒10个。我们实现了一个throttle()
利用嵌入日期/时间的内存缓存的功能。我们使用的api还基于帐户跟踪使用情况。您可能不需要。但这是我们用来限制请求以确保我们始终处于限制范围内的摘要:
private void throttle()
{
var maxPerPeriod = 250;
//If you utilize multiple accounts, you can throttle per account. If not, don't use this:
var keyPrefix = "a_unique_id_for_the_basis_of_throttling";
var intervalPeriod = 300000;//5 minutes
var sleepInterval = 5000;//period to "sleep" before trying again (if the limits have been reached)
var recentTransactions = MemoryCache.Default.Count(x => x.Key.StartsWith(keyPrefix));
while (recentTransactions >= maxPerPeriod)
{
System.Threading.Thread.Sleep(sleepInterval);
recentTransactions = MemoryCache.Default.Count(x => x.Key.StartsWith(keyPrefix));
}
var key = keyPrefix + "_" + DateTime.Now.ToUniversalTime().ToString("yyyyMMddHHmm");
var existing = MemoryCache.Default.Where(x => x.Key.StartsWith(key));
if (existing != null && existing.Any())
{
var counter = 2;
var last = existing.OrderBy(x => x.Key).Last();
var pieces = last.Key.Split('_');
if (pieces.Count() > 2)
{
var lastCount = 0;
if (int.TryParse(pieces[2], out lastCount))
{
counter = lastCount + 1;
}
}
key = key + "_" + counter;
}
var policy = new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.UtcNow.AddMilliseconds(intervalPeriod)
};
MemoryCache.Default.Set(key, 1, policy);
}
我们throttle()
在代码中使用了以下函数:
public override void DoAction()
{
throttle();
var url = ContentUri;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + AccessToken);
request.Accept = "application/json";
WebResponse response = request.GetResponse();
var dataStream = new MemoryStream();
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
//DO STUFF WITH THE DOWNLOADED DATA HERE...
}
dataStream.Close();
response.Close();
}
它实质上在缓存中跟踪您的请求。如果已达到限制,它将暂停直到足够的时间过去,以便您仍在限制之下。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句