HttpClient访问的策略Policy

(一)Policy知识体系图

image

image

(二)代码案例分析

(1)Retry()函数

public static int TestRetry()
{
    int b = 0;
    var policy = Policy.Handle<DivideByZeroException>().Retry(3, (ex, i) => {
        Console.WriteLine($"Retry:{i} 异常信息:{ex.Message}");
    });
    try
    {
        policy.Execute(() => {
            int a = 10;
            b = a / 0;
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"异常:{ex.Message}");
    }
    return b;
}
image
public static int TestTimout()
{
    var policy = Policy.Handle<Exception>().Fallback(() =>
    {
        Console.WriteLine("Fallback");
    }).Wrap(Policy.Handle<Exception>().Retry(3, (ex, i) => {
        Console.WriteLine($"Retry {i}");
    }))
    .Wrap(Policy.Timeout(3, (context, ts, task) =>
    {
        Console.WriteLine("Timeout");
    }));
    var cts = new CancellationTokenSource();
    policy.Execute(ct =>
    {
        for (int i = 0; i < 1000; i++)
        {
            Console.WriteLine($"Execute:{i}");
            Thread.Sleep(1000);
            ct.ThrowIfCancellationRequested();
        }
    }, cts.Token);
    return 0;
}
image

参考指南    https://www.cnblogs.com/TianFang/p/8215718.html

posted @ 2020-09-15 14:57  李华丽  阅读(874)  评论(0编辑  收藏  举报
AmazingCounters.com