在 Servicestack JsonServiceClient Get 方法上实现重试的最佳解决方案是什么?

Pey*_*man 4 c# servicestack

在我的项目中,我使用 Servicestack 从特定 URL 获取数据,此过程是可配置的,我在单独的线程中调用获取数据,如果引发超时错误,我想实现重试。我在 JsonServiceClient 上创建了包装类并在那里实现了重试,但我想知道这种方法的最佳解决方案是什么。

var _client = new JsonServiceClient { Timeout = timeout };
var counter = 0;
do
{
    try
    {
        result = _client.Get<TResponse>(url);
        break;
    }
    catch (Exception exp)
    {
        //Logging exception
    }
}
while (++counter < this.Retry);
Run Code Online (Sandbox Code Playgroud)

Sco*_*ott 5

我在 JsonServiceClient 上创建了包装类并在那里实现了重试,但我想知道这种方法的最佳解决方案是什么。

我同意你的做法。扩展JsonServiceClient和实现您的重试逻辑是可重用性和可维护性的最佳方法,前提是您已经实现了如下内容。

延长 JsonServiceClient

扩展JsonServiceClient以便您可以合并您自己的重试逻辑。然后它很容易在您的代码中重用,而无需在while每次想要发出请求时使用和计数器。

如果你看到JsonServiceClientBase.cs这里的代码,你会注意到所有动词方法如Get<TResponse> Post<TResponse>...Put等都是通过Send<TResponse>(object request)方法调用的。

因此,通过覆盖此方法,我们可以在所有动词上轻松实现重试功能,而无需更改其用法。

public class MyJsonServiceClientWithRetry : JsonServiceClient
{

    public MyJsonServiceClientWithRetry()
    {
    }

    public MyJsonServiceClientWithRetry(int retryAttempts)
    {
        RetryAttempts = retryAttempts;
    }

    public MyJsonServiceClientWithRetry(string baseUri) : base(baseUri)
    {
    }

    public MyJsonServiceClientWithRetry(string syncReplyBaseUri, string asyncOneWayBaseUri) : base(syncReplyBaseUri, asyncOneWayBaseUri)
    {
    }


    // Retry attempts property
    public int RetryAttempts { get; set; }


    public override TResponse Send<TResponse> (string httpMethod, string relativeOrAbsoluteUrl, object request)
    {
        int attempts = RetryAttempts;

        while(true) 
        {
            attempts--;

            try {
                return base.Send<TResponse> (httpMethod, relativeOrAbsoluteUrl, request);
            } catch (WebServiceException webException) {

                // Throw the exception if the number of retries is 0 or we have made a bad request, or are unauthenticated
                if(attempts == 0 || webException.StatusCode == 400 || webException.StatusCode == 401)
                    throw;

            } catch (Exception exception) {

                // Throw the exception if the number of retries is 0
                if(attempts == 0) 
                    throw;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

  • 替换参考JsonServiceClientMyJsonServiceClientWithRetry
  • 设置尝试次数
  • 正常使用客户端。(try/catch超过重试次数后包裹在块中以捕获异常)
var client = new MyJsonServiceClientWithRetry ("http://localhost:8080") {
    RetryAttempts = 3,
    Timeout = new TimeSpan(0, 0, 30)
};


try
{
    var myRequestDto = new MyRequest {
        Name = "John Smith"
    };

    // This request will be attempted 3 times (if there is an exception)
    var response = client.Get<MyResponse>(myRequestDto);

    // Do something with response ...

} catch(Exception ex) {
    // Exception thrown here after 3 attempts (or immediately if status code is 400 / 401)
}
Run Code Online (Sandbox Code Playgroud)

笔记:

如果 aWebServiceException以状态代码 400 或 401 抛出,我不会重试,因为在不更改它的情况下再次尝试此请求似乎是多余的。显然,您可以自定义此逻辑。

如果连接超时,则超时错误将作为WebException. 如果您想专门处理这种情况。

我希望这有帮助。