写在前面
polly 是一个 .net 弹性和瞬态故障处理库,允许开发人员以 fluent 和线程安全的方式来实现重试、断路、超时、隔离和回退策略。
polly 的七种策略介绍
重试(retry): 当出现故障时自动进行重试
断路(circuit-breaker):当系统遇到严重问题时,快速回馈失败比让用户/调用者等待要好,限制系统出错的体量,有助于系统恢复。
超时(timeout):当系统超过一定时间的等待,我们就几乎可以判断不可能会有成功的结果,直接去干别的事情。
隔离(bulkhead isolation):当系统的一处出现故障时,可能促发多个失败的调用,很容易耗尽主机的资源(如 cpu)。下游系统出现故障可能导致上游的故障的调用,甚至可能蔓延到导致系统崩溃。所以要将可控的操作限制在一个固定大小的资源池中,以隔离有潜在可能相互影响的操作。
回退(fallback):有些错误无法避免,就要有备用的方案。这个就像浏览器不支持一些新的 css 特性就要额外引用一个 polyfill 一样。一般情况,当无法避免的错误发生时,我们要有一个合理的返回来代替失败。
缓存(cache):一般我们会把频繁使用且不会怎么变化的资源缓存起来,以提高系统的响应速度。如果不对缓存资源的调用进行封装,那么我们调用的时候就要先判断缓存中有没有这个资源,有的话就从缓存返回,否则就从资源存储的地方(比如数据库)获取后缓存起来,再返回,而且有时还要考虑缓存过期和如何更新缓存的问题。polly 提供了缓存策略的支持,使得问题变得简单。
策略包(policy wrap):一种操作会有多种不同的故障,而不同的故障处理需要不同的策略。这些不同的策略必须包在一起,作为一个策略包,才能应用在同一种操作上。这就是文章开头说的 polly 的弹性,即各种不同的策略能够灵活地组合起来。
通过nuget安装polly类库:
官方项目地址: https://github.com/app-vnext/polly
代码实现
/// <summary> /// fallback => 当出现故障,则进入降级动作 /// </summary> public static void case1() { isyncpolicy policy = policy.handle<argumentexception>() .fallback(() => { console.writeline("error occured"); }); policy.execute(() => { console.writeline("job start"); throw new argumentexception("hello polly!"); console.writeline("job end"); }); } /// <summary> /// retry => 重试 /// </summary> public static void case2() { isyncpolicy policy = policy.handle<exception>().retry(3); try { policy.execute(() => { console.writeline("job start"); if (datetime.now.second % 10 != 0) { throw new exception("special error occured"); } console.writeline("job end"); }); } catch (exception ex) { console.writeline("there's one unhandled exception : " + ex.message); } } /// <summary> /// circuitbreaker => 短路保护 /// </summary> public static void case3() { // stop for 10s after retry 6 times isyncpolicy policy = policy.handle<exception>() .circuitbreaker(6, timespan.fromseconds(10)); while (true) { try { policy.execute(() => { console.writeline("job start"); throw new exception("special error occured"); console.writeline("job end"); }); } catch (exception ex) { console.writeline("there's one unhandled exception : " + ex.message); } thread.sleep(500); } } /// <summary> /// timeout 与 wrap => wrap是指策略封装,可以把多个isyncpolicy合并到一起执行。timeout则是指超时处理,但是超时策略一般不能直接使用,而是其其他策略封装到一起使用。 /// </summary> public static void case4() { try { isyncpolicy policyexception = policy.handle<timeoutrejectedexception>() .fallback(() => { console.writeline("fallback"); }); isyncpolicy policytimeout = policy.timeout(3, polly.timeout.timeoutstrategy.pessimistic); isyncpolicy mainpolicy = policy.wrap(policytimeout, policyexception); mainpolicy.execute(() => { console.writeline("job start..."); thread.sleep(5000); throw new exception(); console.writeline("job end..."); }); } catch (exception ex) { console.writeline($"unhandled exception : {ex.gettype()} : {ex.message}"); } } /// <summary> /// 异步方法 /// </summary> public static async void case5() { var policy = policy<byte[]>.handle<exception>() .fallbackasync(async c => { console.writeline("executed error!"); return new byte[0]; }, async r => { console.writeline(r.exception); }); policy.wrapasync(policy.timeoutasync(5, timeoutstrategy.pessimistic, async (context, timespan, task) => { console.writeline("timeout!"); })); var bytes = await policy.executeasync(async () => { console.writeline("start job"); httpclient httpclient = new httpclient(); var result = await httpclient.getbytearrayasync("https://img-blog.csdnimg.cn/img_convert/50f2b9069f40b88ea8348492d56abb87.png"); console.writeline("finish job"); return result; }); console.writeline($"length of bytes : {bytes.length}"); }
调用示例
case1:
case2:
case3:
到此这篇关于.net中弹性和瞬时处理库polly的使用详解的文章就介绍到这了,更多相关.net polly内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论