1

我正在尝试使用 Polly 测试连接字符串是否为空。如果为空,我想使用 CircuitBreaker 尝试 3 次,消息应该会在 Console 窗口中输出。

Policy policy = null;

// Break the circuit after the specified number of exceptions
// and keep circuit broken for the specified duration.
policy = Policy
               .Handle<NullReferenceException>()
               .CircuitBreaker(3, TimeSpan.FromSeconds(30)); 
try
   {
     string connected = policy.Execute(() => repository.GetConnectionString());
   }

catch (Exception ex)
      {
         Console.WriteLine("{0}",ex.Message);               
      }     

GetConnectionString 方法是:

public string GetConnectionString()
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;
        return conn.ConnectionString;
    }

为了对此进行测试,我在 App.config 中更改了连接字符串名称。

但是它似乎没有处理 NullReference 异常。

当我调试应用程序时 - 它打开 CircuitBreakerEngine.cs not found 并仅打印“对象引用未设置为对象的实例”。

预期:打印未设置为对象实例三次的对象引用和来自断路异常的消息

4

1 回答 1

5

I believe you have misunderstood what the CircuitBreaker policy does, as described at this similar question: Polly framework CircuitBreakerAsync does not retry if exception occur

A circuit-breaker does not of itself orchestrate any retries. Rather, it exists to measure the rate of faults on delegates executed through it - and trip the circuit if the fault rate becomes too high. As its purpose is only as a measuring-and-breaking device, it indeed rethrows exceptions from delegates executed through it: hence the NullReferenceException you are seeing rethrown.

EDIT: This behaviour of the circuit-breaker, and its difference from retry, is also clearly described in the Polly wiki, at: https://github.com/App-vNext/Polly/wiki/Circuit-Breaker

To do what I think you want to do, you need to combine retry policy with circuit breaker policy as described at Polly framework CircuitBreakerAsync does not retry if exception occur. Polly now offers PolicyWrap to make combining policies easy.

于 2016-05-08T15:02:35.863 回答