Policy.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using Polly;
  3. namespace WMS.Util
  4. {
  5. public static class PolicyHelper
  6. {
  7. #region 执行策略
  8. /// <summary>
  9. /// 重试次数策略
  10. /// </summary>
  11. /// <param name="time"></param>
  12. /// <param name="exAction">错误处理</param>
  13. /// <returns></returns>
  14. public static Policy GetRetryTimesPolicy(int time, Action<Exception> exAction = null)
  15. {
  16. if (time <= 0) return default(Policy);
  17. Policy policy = null;
  18. if (exAction == null)
  19. {
  20. policy = Policy
  21. .Handle<Exception>()
  22. .Retry(time);
  23. }
  24. else
  25. {
  26. policy = Policy
  27. .Handle<Exception>()
  28. .Retry(time, (ex, count) =>
  29. {
  30. exAction(ex);
  31. });
  32. }
  33. return policy;
  34. }
  35. /// <summary>
  36. /// 超时策略
  37. /// </summary>
  38. /// <param name="milliseconds"></param>
  39. /// <returns></returns>
  40. public static Policy GetTimeOutPolicy(int milliseconds)
  41. {
  42. if (milliseconds <= 0) return default(Policy);
  43. var policy = Policy
  44. .Timeout(TimeSpan.FromMilliseconds(milliseconds));
  45. return policy;
  46. }
  47. /// <summary>
  48. /// 回退策略
  49. /// </summary>
  50. /// <param name="method"></param>
  51. /// <returns></returns>
  52. public static Policy GetFallBackPolicy(Action method)
  53. {
  54. if (method==null) return default(Policy);
  55. var policy=Policy
  56. .Handle<Exception>()
  57. .Fallback(method);
  58. return policy;
  59. }
  60. #endregion
  61. }
  62. }