3

我正在向 Polly 发出 HTTP 请求。我想在数组中的每个代理等待 1 秒后重试一次。
我怎样才能做得更好?
我怎么能在 F# 中做到这一点?

public static Result RequestWithRetry(string url, string[] proxies, string username, string password)
{
    if (proxies == null) throw new ArgumentNullException("null proxies array");
    var client = new WebClient { Credentials = new NetworkCredential(username, password) };
    var result = String.Empty;
    var proxyIndex = 0;

    var policy = Policy
            .Handle<Exception>()
            .WaitAndRetry(new[]
                {
                    TimeSpan.FromSeconds(1)
                }, (exception, timeSpan) => proxyIndex++);

    policy.Execute(() =>
    {                 
        if (proxyIndex >= proxies?.Length) throw new Exception($"Exhausted proxies: {String.Join(", ", proxies)}");

        client.Proxy = new WebProxy(proxies?[proxyIndex]) { UseDefaultCredentials = true };
        result = client.DownloadString(new Uri(url));
    });

    return new Result(value: result, proxy: proxies[proxyIndex]);
}
4

2 回答 2

3

您可以尝试更多功能的方式Result<'TOk,'TError>Async<T>

open System.Net
open System

type Request =
    { Url      : string
      Proxies  : string list
      UserName : string
      Password : string }

let requestWithRetry request =
    let client = 
        new WebClient (
            Credentials = new NetworkCredential(
                request.UserName,
                request.Password))
    let uri = Uri request.Url
    let rec retry = function
        | [] -> Error "Exhausted proxies" |> async.Return
        | (proxy:string)::rest -> async {
            try 
                do client.Proxy <- new WebProxy(proxy, UseDefaultCredentials = true)
                let! response = client.AsyncDownloadString uri
                return Ok (response, proxy)
            with _ ->
                do! Async.Sleep 1000
                return! retry rest
        }
    retry request.Proxies
于 2018-07-13T13:17:07.137 回答
0

我能够把这个翻译放在一起。我不是很喜欢它,尽管我确实学到了很多关于 F# 的知识以及Action在这个过程中。

type Result = { Value: string; Proxy: string }

let request (proxies:string[]) (username:string) (password:string) (url:string) : Result =                   
    if (proxies = null) then raise <| new ArgumentNullException()

    use client = new WebClient()
    client.Credentials <- NetworkCredential(username, password)
    let mutable result = String.Empty;
    let mutable proxyIndex = 0;

    let policy =
        Policy
            .Handle<Exception>()
            .WaitAndRetry(
                sleepDurations = [| TimeSpan.FromSeconds(1.0) |], 
                onRetry = Action<Exception, TimeSpan>(fun _ _ -> proxyIndex <- proxyIndex + 1)
                )

    let makeCall () =
        if (proxyIndex >= proxies.Length) 
        then failwith ("Exhausted proxies: " + String.Join(", ", proxies))
        else
            let proxy = WebProxy(proxies.[proxyIndex])
            proxy.UseDefaultCredentials <- true
            client.Proxy <- proxy
            result <- client.DownloadString(new Uri(url));

    policy.Execute(Action makeCall)

    { Result.Value = result; Proxy = proxies.[proxyIndex]}
于 2018-07-13T01:39:53.770 回答