5.4超时与重试

为单次请求设置超时时长。

设置超时时间#

为单次请求设置超时时长。

HTTP 声明式请求通过 TimeoutAttribute 特性来设置超时时间。相应的 HTTP 声明式提取器实现为 TimeoutDeclarativeExtractor 类型,该类型负责解析 TimeoutAttribute 特性并构建 HttpRequestBuilder 实例所需的超时时间配置。

cs
// 在接口定义上应用,影响所有方法[Timeout(100_000)]  // 100 秒public interface IHttpService : IHttpDeclarative{    [Get("https://furion.net/")]    Task<string> GetStringAsync();    // 在方法上应用    [Timeout(200_000)]   // 200 秒    [Get("https://furion.net/")]    Task<string> GetStringAsync();}

TimeoutAttribute 包含以下构造函数和属性:

  • 构造函数

    • new(milliseconds):作用于方法或接口,设置超时时间。
  • 属性

    • Timeout:超时时间(毫秒)(double 类型)。

配置重试策略#

为单次请求配置重试策略。默认情况下,若已配置重试策略,则当请求出现未被抑制的异常时,将自动触发重试机制。

HTTP 声明式请求通过 RetryAttribute 特性来配置重试策略。相应的 HTTP 声明式提取器实现为 RetryDeclarativeExtractor 类型,该类型负责解析 RetryAttribute 特性并构建 HttpRequestBuilder 实例所需的重试策略配置。

cs
// 在接口定义上应用,影响所有方法[Retry(3)]  // 最大重试 3 次public interface IHttpService : IHttpDeclarative{    [Get("https://furion.net/")]    Task<string> GetStringAsync();    // 在方法上应用    [Retry(10)]   // 最大重试 10 次    [Get("https://furion.net/")]    Task<string> GetStringAsync();    [Retry(10, 1000)]   // 配置重试间隔时间    [Get("https://furion.net/")]    Task<string> GetStringAsync();    [Retry(10, RetryStatusCodes = [401])]   // 对特定 HTTP 状态码进行重试    [Get("https://furion.net/")]    Task<string> GetStringAsync();    [Retry(10, RetryExceptionTypes = [typeof(InvalidOperationException)])]   // 对特定异常类型进行重试    [Get("https://furion.net/")]    Task<string> GetStringAsync();    [Retry(RetryIndefinitely = true)]   // 设置无限重试,直到成功    [Get("https://furion.net/")]    Task<string> GetStringAsync();}

RetryAttribute 包含以下构造函数和属性:

  • 构造函数

    • new(maxRetries):作用于方法或接口,设置最大重试次数(0 表示不重试)。
    • new(maxRetries, retryInterval):作用于方法或接口,设置最大重试次数(0 表示不重试)和重试间隔基准时间(毫秒)。
  • 属性

    • MaxRetries:最大重试次数(int 类型)。默认值为 0,表示不重试。如果设置了 RetryIntervals,此值将自动被覆盖为数组长度。
    • RetryInterval:重试间隔基准时间(毫秒)(double 类型)。默认值为 1000 毫秒。仅在未设置 RetryIntervals 时生效。
    • UseExponentialBackoff:是否采用指数退避重试(bool 类型)。默认值为:false。当设置为 true 时,每次重试间隔 = RetryInterval * 2^(retry-1)。仅在未设置 RetryIntervals 时生效。
    • RetryIntervals:自定义重试间隔数组(毫秒)(double[]? 类型)。如果设置了此属性,则重试次数将等于数组长度,MaxRetriesUseExponentialBackoff 将被忽略。每次重试将按顺序使用数组中对应索引的间隔时间。
    • RetryStatusCodes:需要重试的 HTTP 状态码集合(int[]? 类型)。若为空,则仅重试因异常引发的失败。
    • RetryExceptionTypes:需要重试的异常类型集合(Type[]? 类型)。若为空,则对所有 Exception 进行重试(受 MaxRetries 限制)。
    • RetryIndefinitely:是否无限重试,直到成功(bool 类型)。默认值为:false。当设置为 true 时,MaxRetriesRetryIntervals 的长度将被忽略,一直重试直到成功或发生不可重试的异常。