Contentful.net中出现api限速时如何编写重试策略?

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

我有以下代码调用内容丰富的cms。这是我的 webhook 调用的代码。现在我对 C# 中的重试机制还很陌生。

Contentful发生限速错误时如何实现重试? Contentful cms 的技术限制为每秒 10 次调用。如果任何调用失败,那么我们需要使用重试策略重试它们。

关于如何开始的任何想法。

public async Task HandleRedirectAsync(string slug, string previousSlug, string contentTypeId, string entryId)
{
    var endpoint = "entries";
    if (!string.IsNullOrEmpty(slug))
    {
        var isPreviousSlugNotEmpty = !String.IsNullOrEmpty(previousSlug);
        var isSlugAndPreviousSlugSame = slug == previousSlug;
      

        if (isPreviousSlugNotEmpty && isSlugAndPreviousSlugSame)
        {
            return;
        }
        //Delete API call to cms 
        await DeleteRedirectLoopsAsync(slug, contentTypeId, endpoint);

        
        if (isPreviousSlugNotEmpty && !isSlugAndPreviousSlugSame)
        {
            await CreateAndPublishRedirectEntryAsync(entryId, previousSlug, slug);
        }
        await UpdateEntryAsync(contentTypeId, entryId);
    }
}
c# rate-limiting contentful polly retry-logic
1个回答
0
投票

您可以看看 .NET SDK 中是如何处理的:https://github.com/contentful/contentful.net

基本上,如果返回 429 结果,则请求被克隆,等待任务会执行指定的毫秒数,然后再次发送请求。

相关代码如下:

if((int)response.StatusCode == 429 && _options.MaxNumberOfRateLimitRetries > 0)
            {
                //Limit retries to 10 regardless of config
                for (var i = 0; i < _options.MaxNumberOfRateLimitRetries && i < 10; i++)
                {
                    try
                    {
                        await CreateExceptionForFailedRequest(response).ConfigureAwait(false); ;
                    }
                    catch (ContentfulRateLimitException ex)
                    {
                        await Task.Delay(ex.SecondsUntilNextRequest * 1000).ConfigureAwait(false);
                    }
                   
                    var clonedMessage = await CloneHttpRequest(response.RequestMessage);

                    response = await _httpClient.SendAsync(clonedMessage).ConfigureAwait(false);

                    if (response.IsSuccessStatusCode)
                    {
                        return response;
                    }
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.