Handle faults that may take a variable amount of time to rectify when connecting to a remote service or resource. This pattern can improve the stability and resiliency of an application.
在連接到一個遠程服務或資源時,處理故障可能需要一個變量的時間來糾正。這種模式可以提高應用程序的穩定性和彈性。
Context and Problem 背景與問題
In a distributed environment such as the cloud, where an application performs operations that access remote resources and services, it is possible for these operations to fail due to transient faults such as slow network connections, timeouts, or the resources being overcommitted or temporarily unavailable. These faults typically correct themselves after a short period of time, and a robust cloud application should be prepared to handle them by using a strategy such as that described by the Retry pattern.
在分布式環境中如云,在應用程序執行如訪問遠程的資源和服務等操作,這些業務由于瞬時故障,如網絡連接慢超時失敗,或資源投入暫時不可用。這些故障通常是在經過一段短的時間后有恢復正常,一個強大的云應用程序應該使用一種策略來處理這種情況,如通過重試模式描述。
However, there may also be situations where faults are due to unexpected events that are less easily anticipated, and that may take much longer to rectify. These faults can range in severity from a partial loss of connectivity to the complete failure of a service. In these situations it may be pointless for an application to continually retry performing an operation that is unlikely to succeed, and instead the application should quickly accept that the operation has failed and handle this failure accordingly.
然而,也有可能是由于突發事件的情況下,是不容易預料到的,可能需要更長的時間來糾正。這些故障可以從一個服務的完全故障的連接的部分損失的嚴重程度的范圍內。在這種情況下,它可能是毫無意義的一個應用程序不斷重試執行的操作是不可能成功的,相反,應用程序應該迅速接受的操作失敗,并處理此故障相應。
Additionally, if a service is very busy, failure in one part of the system may lead to cascading failures. For example, an operation that invokes a service could be configured to implement a timeout, and reply with a failure message if the service fails to respond within this period. However, this strategy could cause many concurrent requests to the same operation to be blocked until the timeout period expires. These blocked requests might hold critical system resources such as memory, threads, database connections, and so on. Consequently, these resources could become exhausted, causing failure of other possibly unrelated parts of the system that need to use the same resources. In these situations, it would be preferable for the operation to fail immediately, and only attempt to invoke the service if it is likely to succeed. Note that setting a shorter timeout may help to resolve this problem, but the timeout should not be so short that the operation fails most of the time, even if the request to the service would eventually succeed.
此外,如果一個服務是非常繁忙的,系統中的一個部分的故障可能會導致級聯故障。例如,調用服務的操作可以配置為執行超時,如果服務未能在這個時間內響應,將回復一個失敗消息。然而,這種策略可能會導致許多并發請求到同一個操作被阻塞,直到超時期限屆滿。這些阻塞的請求可能會存儲關鍵的系統資源,如內存、線程、數據庫連接等。因此,這些資源可能會枯竭,導致其他可能不相關的部分,需要使用相同的資源系統的故障。在這種情況下,它將是優選的操作立即失敗,并且只有嘗試調用服務,如果它有可能成功。請注意,設置較短的超時可能有助于解決這個問題,但超時不應該如此短,操作失敗的大部分時間,即使對服務的請求最終會成功。
Solution 解決方案
The Circuit Breaker pattern can prevent an application repeatedly trying to execute an operation that is likely to fail, allowing it to continue without waiting for the fault to be rectified or wasting CPU cycles while it determines that the fault is long lasting. The Circuit Breaker pattern also enables an application to detect whether the fault has been resolved. If the problem appears to have been rectified, the application can attempt to invoke the operation.
斷路器的模式可以防止一個應用程序反復嘗試執行一個可能會失敗的操作,讓它繼續不等待故障的糾正或浪費處理器周期,而它決定了故障是長期持久的。斷路器的模式也使一個應用程序來檢測故障是否已得到解決。如果出現問題,該應用程序可以嘗試調用操作。
Note:
The purpose of the Circuit Breaker pattern is different from that of the Retry Pattern. The Retry Pattern enables an application to retry an operation in the expectation that it will succeed. The Circuit Breaker pattern prevents an application from performing an operation that is likely to fail. An application may combine these two patterns by using the Retry pattern to invoke an operation through a circuit breaker. However, the retry logic should be sensitive to any exceptions returned by the circuit breaker and abandon retry attempts if the circuit breaker indicates that a fault is not transient.
斷路器模式的目的不同于重試模式。重試模式允許應用程序重試操作,以期望它會成功。斷路器的模式可以防止一個應用程序進行操作,可能會失敗。一個應用程序可以將這兩者結合起來,通過使用重試模式調用一個操作通過一個斷路器。然而,重試邏輯應該是敏感的斷路器返回的任何異常,并放棄重試嘗試,如果斷路器表明故障是不暫態。
A circuit breaker acts as a proxy for operations that may fail. The proxy should monitor the number of recent failures that have occurred, and then use this information to decide whether to allow the operation to proceed, or simply return an exception immediately.
斷路器作為可能失敗的操作的代理。代理應該監測最近發生的故障數,然后使用此信息來決定是否允許該操作進行,或者立即返回一個異常。
•Closed: The request from the application is routed through to the operation. The proxy maintains a count of the number of recent failures, and if the call to the operation is unsuccessful the proxy increments this count. If the number of recent failures exceeds a specified threshold within a given time period, the proxy is placed into the Open state. At this point the proxy starts a timeout timer, and when this timer expires the proxy is placed into the Half-Open state.
關閉:應用程序的請求被路由到操作。代理維護最近失敗的數目的計數,如果調用操作失敗,則代理遞增此計數。如果在給定時間段內,最近的故障數超過了指定的閾值,則該代理被放置在打開狀態。在這一點上,代理開始一個超時計時器,當這個計時器過期時,代理被放置到半開放狀態。
Note:
The purpose of the timeout timer is to give the system time to rectify the problem that caused the failure before allowing the application to attempt to perform the operation again.
超時計時器的目的是給系統時間來糾正在允許應用程序嘗試再次執行操作之前所導致的故障的問題。
• Open: The request from the application fails immediately and an exception is returned to the application.
打開:應用程序的請求失敗,立即并一個異常返回到應用程序。
Half-Open: A limited number of requests from the application are allowed to pass through and invoke the operation. If these requests are successful, it is assumed that the fault that was previously causing the failure has been fixed and the circuit breaker switches to the Closed state (the failure counter is reset). If any request fails, the circuit breaker assumes that the fault is still present so it reverts back to the Open state and restarts the timeout timer to give the system a further period of time to recover from the failure.
半開放:應用程序有限的請求可以通過和調用操作。如果這些請求是成功的,它被假定的故障,是以前造成的故障已被固定和斷路器開關的閉合狀態(故障計數器復位)。如果請求失敗,斷路器假定故障仍然存在,那么它恢復到打開狀態并重新啟動超時定時器給系統進一步的時間從故障中恢復。
Note:
The Half-Open state is useful to prevent a recovering service from suddenly being inundated with requests. As a service recovers, it may be able to support a limited volume of requests until the recovery is complete, but while recovery is in progress a flood of work may cause the service to time out or fail again.
半開放狀態是有用的,以防止恢復服務突然被淹沒的請求。當服務恢復時,它可能會支持有限的請求數量,直到恢復完成,但當恢復是在進行中的工作時,可能會導致服務超時或再次失敗。
Figure 1 illustrates the states for one possible implementation of a circuit breaker.
圖1說明了一個斷路器的一個可能實現的狀態。
Figure 1 - Circuit Breaker states 圖1 -斷路器狀態
Note that, in Figure 1, the failure counter used by the Closed state is time-based. It is automatically reset at periodic intervals. This helps to prevent the circuit breaker from entering the Open state if it experiences occasional failures; the failure threshold that trips the circuit breaker into the Open state is only reached when a specified number of failures have occurred during a specified interval. The success counter used by the Half-Open state records the number of successful attempts to invoke the operation. The circuit breaker reverts to the Closed state after a specified number of consecutive operation invocations have been successful. If any invocation fails, the circuit breaker enters the Open state immediately and the success counter will be reset the next time it enters the Half-Open state.
注意,在圖1中,由封閉狀態的故障計數器時間。它是自動重置周期間隔。這有助于防止斷路器進入開放狀態,如果它偶爾出現故障,跳閘斷路器進入開放狀態的故障閾值時,只有達到指定數量的故障發生在指定的時間間隔。半開放狀態記錄的成功計數器記錄成功嘗試調用操作的次數。斷路器恢復到關閉狀態指定數量的連續操作調用后已成功。如果任何調用失敗,斷路器立即進入打開狀態,并在下一次進入半開放狀態時,該斷路器將被重置。
Note:
How the system recovers is handled externally, possibly by restoring or restarting a failed component or repairing a network connection.
系統如何恢復處理外部,可能通過恢復或重新啟動失敗的組件或修復網絡連接。
Implementing the circuit breaker pattern adds stability and resiliency to a system, offering stability while the system recovers from a failure and minimizing the impact of this failure on performance. It can help to maintain the response time of the system by quickly rejecting a request for an operation that is likely to fail, rather than waiting for the operation to time out (or never return). If the circuit breaker raises an event each time it changes state, this information can be used to monitor the health of the part of the system protected by the circuit breaker, or to alert an administrator when a circuit breaker trips to the Open state.
實現斷路器模式增加了系統的穩定性和彈性,提供穩定而系統的破壞和減少這種故障對性能的影響恢復。它可以幫助維持系統的響應時間,快速拒絕一個操作的請求,可能會失敗,而不是等待操作超時(或不返回)。如果斷路器每一次改變狀態,這個信息可以用來監測斷路器保護系統的一部分的健康狀況,或者當斷路器跳閘時,向系統管理員發出警報。
The pattern is customizable and can be adapted according to the nature of the possible failure. For example, you can apply an increasing timeout timer to a circuit breaker. You could place the circuit breaker in the Open state for a few seconds initially, and then if the failure has not been resolved increase the timeout to a few minutes, and so on. In some cases, rather than the Open state returning failure and raising an exception, it could be useful to return a default value that is meaningful to the application.
該模式是可定制的,可以根據可能的故障的性質進行調整。例如,您可以將超時計時器應用于斷路器。你可以先將斷路器在開狀態的幾秒鐘,然后,如果故障一直沒有得到解決,增加超時幾分鐘,等等。在某些情況下,而不是打開狀態返回失敗,并引發一個異常,它可能是有用的返回一個默認值,這對應用程序有意義的。
Issues and Considerations 問題和注意事項
•Exception Handling. An application invoking an operation through a circuit breaker must be prepared to handle the exceptions that could be raised if the operation is unavailable. The way in which such exceptions are handled will be application specific. For example, an application could temporarily degrade its functionality, invoke an alternative operation to try to perform the same task or obtain the same data, or report the exception to the user and ask them to try again later.
異常處理。應用程序調用一個操作通過斷路器,必須準備好處理可以提出的異常,如果操作不可用。此類異常處理的方式將是應用程序特定的。例如,一個應用程序可能會暫時降低它的功能,調用另一個操作來執行相同的任務,或者獲得相同的數據,或者向用戶報告異常并要求他們稍后再試。
• Types of Exceptions. A request may fail for a variety of reasons, some of which may indicate a more severe type of failure than others. For example, a request may fail because a remote service has crashed and may take several minutes to recover, or failure could be caused by a timeout due to the service being temporarily overloaded. A circuit breaker may be able to examine the types of exceptions that occur and adjust its strategy depending on the nature of these exceptions. For example, it may require a larger number of timeout exceptions to trip the circuit breaker to the Open state compared to the number of failures due to the service being completely unavailable.
異常類型。一個請求可能會失敗,因為有各種各樣的原因,其中一些可能表明一個更嚴重的異常類型。例如,一個請求可能會失敗,因為遠程服務已經崩潰,可能需要幾分鐘的時間來恢復,或故障可能是由于臨時超載的服務造成的超時。斷路器可以檢查的類型的異常,發生和調整其策略,根據這些異常的性質。例如,它可能需要一個更大數量的超時異常跳閘斷路器的開放狀態相比,由于服務是完全不可用的故障數。
• Logging. A circuit breaker should log all failed requests (and possibly successful requests) to enable an administrator to monitor the health of the operation that it encapsulates.
日志記錄。斷路器應記錄所有失敗的請求(可能成功的請求)來幫助管理員監控手術所有封裝的操作。
• Testing Failed Operations. In the Open state, rather than using a timer to determine when to switch to the Half-Open state, a circuit breaker may instead periodically ping the remote service or resource to determine whether it has become available again. This ping could take the form of an attempt to invoke an operation that had previously failed, or it could use a special operation provided by the remote service specifically for testing the health of the service, as described by the Health Endpoint Monitoring pattern.
• Concurrency. The same circuit breaker could be accessed by a large number of concurrent instances of an application. The implementation should not block concurrent requests or add excessive overhead to each call to an operation.
并發。同樣的斷路器可以通過大量的并發實例進行訪問。執行不應該阻止并發請求或在每次調用操作中添加過多的開銷。
• Resource Differentiation. Be careful when using a single circuit breaker for one type of resource if there might be multiple underlying independent providers. For example, in a data store that comprises multiple shards, one shard may be fully accessible while another is experiencing a temporary issue. If the error responses in these scenarios are conflated, an application may attempt to access some shards even when failure is highly likely, while access to other shards may be blocked even though it is likely to succeed.
資源分化。當使用一個單一的斷路器一種資源,如果可能有多個潛在的獨立供應商。例如,在數據存儲,包括多個碎片,一個碎片可以完全訪問另一個正在經歷一個暫時的問題。如果在這些情況下,錯誤反應混為一談,一個應用程序試圖訪問一些碎片即使失敗是很有可能的,而訪問其他碎片可能堵塞,即使是有可能成功的。
• Accelerated Circuit Breaking. Sometimes a failure response can contain enough information for the circuit breaker implementation to know it should trip immediately and stay tripped for a minimum amount of time. For example, the error response from a shared resource that is overloaded could indicate that an immediate retry is not recommended and that the application should instead try again in a few minutes time.
加速電路斷開。有時一個故障響應可以包含足夠的信息,斷路器的實施,知道它應該跳閘,并停留在一個最小的時間被絆倒。例如,一個被重載的共享資源的錯誤響應可以指示立即重試不被推薦,應用程序應該在幾分鐘時間內再試一次。
Note:
The HTTP protocol defines the “HTTP 503 Service Unavailable” response that can be returned if a requested service is not currently available on a particular web server. This response can include additional information, such as the anticipated duration of the delay.
• Replaying Failed Requests. In the Open state, rather than simply failing quickly, a circuit breaker could also record the details of each request to a journal and arrange for these requests to be replayed when the remote resource or service becomes available.
•重試失敗的請求。在開放的狀態,而不是簡單的不快,斷路器還可以記錄每個請求的細節,日記和安排這些請求將重播當遠程服務或資源可用。
When to Use this Pattern 什么時候使用這種模式
Use this pattern:
•To prevent an application from attempting to invoke a remote service or access a shared resource if this operation is highly likely to fail.
This pattern might not be suitable:
•For handling access to local private resources in an application, such as in-memory data structure. In this environment, using a circuit breaker would simply add overhead to your system.
•As a substitute for handling exceptions in the business logic of your applications.
使用這種模式:
防止一個應用程序試圖調用遠程服務或訪問共享資源,如果這個操作很可能失敗。
這種模式可能不適合:
在一個應用程序中處理訪問本地的私有資源,例如內存數據結構。在這種環境中,使用斷路器會增加系統的開銷。
在應用程序的業務邏輯中處理異常的替代品。
Example
In a web application, several of the pages are populated with data retrieved from an external service. If the system implements minimal caching, most hits to each of these pages will cause a round trip to the service. Connections from the web application to the service could be configured with a timeout period (typically 60 seconds), and if the service does not respond in this time the logic in each web page will assume that the service is unavailable and throw an exception.
在一個網絡應用程序中,有幾個頁面被從外部服務中檢索到的數據填充。如果該系統實現了最小的緩存,這些頁面中的大多數點擊將導致一個回合的服務。從網絡應用程序到服務的連接可以配置一個超時周期(通常為60秒),如果在這個時間內的服務沒有響應,在每個網頁中的邏輯將假設該服務是不可用,并拋出異常。
However, if the service fails and the system is very busy, users could be forced to wait for up to 60 seconds before an exception occurs. Eventually resources such as memory, connections, and threads could be exhausted, preventing other users from connecting to the system—even if they are not accessing pages that retrieve data from the service.
但是,如果服務失敗,系統非常忙,用戶可以在一個異常發生前等待60秒。最終資源,如內存,連接和線程可能會用盡,防止其他用戶連接到系統,即使他們不訪問的網頁,檢索數據的服務。
Scaling the system by adding further web servers and implementing load balancing may delay the point at which resources become exhausted, but it will not resolve the issue because user requests will still be unresponsive and all web servers could still eventually run out of resources.
通過添加進一步的網絡服務器和實現負載平衡縮放系統可能會延遲資源變得疲憊的點,但它不會解決這個問題,因為用戶請求仍然是不響應的,所有的網絡服務器仍然可以最終耗盡資源。
Wrapping the logic that connects to the service and retrieves the data in a circuit breaker could help to alleviate the effects of this problem and handle the service failure more elegantly. User requests will still fail, but they will fail more quickly and the resources will not be blocked.
包裝的邏輯連接到服務和檢索的數據在一個斷路器可以幫助緩解這個問題的影響,并處理更優雅的服務故障。用戶請求仍然會失敗,但他們會更快地失敗,資源也不會被阻塞。
The CircuitBreaker class maintains state information about a circuit breaker in an object that implements the ICircuitBreakerStateStore interface shown in the following code.
斷路器類保持在實行以下代碼中所示的ICircuitBreakerStateStore接口對象的斷路器狀態信息。
interface ICircuitBreakerStateStore { CircuitBreakerStateEnum State { get; } Exception LastException { get; } DateTime LastStateChangedDateUtc { get; } void Trip(Exception ex); void Reset(); void HalfOpen(); bool IsClosed { get; } }
The State property indicates the current state of the circuit breaker, and will be one of the values Open, HalfOpen, or Closed as defined by the CircuitBreakerStateEnum enumeration. The IsClosed property should be true if the circuit breaker is closed, but false if it is open or half-open. The Trip method switches the state of the circuit breaker to the open state and records the exception that caused the change in state, together with the date and time that the exception occurred. The LastException and the LastStateChangedDateUtc properties return this information. The Reset method closes the circuit breaker, and the HalfOpen method sets the circuit breaker to half-open.
State屬性表示斷路器的當前狀態,并將其中一個值,halfopen,或關閉的CircuitBreakerStateEnum枚舉定義。如果IsClosed屬性是真的,但假如果是開放或半開放。跳閘方法將斷路器的狀態切換到打開狀態,并記錄引起狀態變化的異常,以及異常發生的日期和時間。的LastException和LastStateChangedDateUtc屬性返回此信息。復位方法關閉斷路器,和HalfOpen方法設置斷路器半開。
The InMemoryCircuitBreakerStateStore class in the example contains an implementation of the ICircuitBreakerStateStore interface. The CircuitBreaker class creates an instance of this class to hold the state of the circuit breaker.
例子中的InMemoryCircuitBreakerStateStore 類包含的ICircuitBreakerStateStore 接口的實現。斷路器類創建該類的實例來對斷路器的狀態。
The ExecuteAction method in the CircuitBreaker class wraps an operation (in the form of an Action delegate) that could fail. When this method runs, it first checks the state of the circuit breaker. If it is closed (the local IsOpen property, which returns true if the circuit breaker is open or half-open, is false) the ExecuteAction method attempts to invoke the Action delegate. If this operation fails, an exception handler executes the TrackException method, which sets the state of the circuit breaker to open by calling the Trip method of the InMemoryCircuitBreakerStateStore object. The following code example highlights this flow.
在CircuitBreaker類的ExecuteAction 方法包裝操作(在一個行動代表的形式),可能會失敗。當該方法運行時,它首先檢查斷路器的狀態。如果是封閉的(當地IsOpen屬性,它返回true,如果斷路器是開放或半開放的,是虛假的)的ExecuteAction方法試圖調用Action委托。如果操作失敗,異常處理程序執行TrackException方法,使斷路器的狀態通過調用對象的方法InMemoryCircuitBreakerStateStore行程開。下面的代碼示例突出了該流程。
public class CircuitBreaker { private readonly ICircuitBreakerStateStore stateStore = CircuitBreakerStateStoreFactory.GetCircuitBreakerStateStore(); private readonly object halfOpenSyncObject = new object (); ... public bool IsClosed { get { return stateStore.IsClosed; } } public bool IsOpen { get { return !IsClosed; } } public void ExecuteAction(Action action) { ... if (IsOpen) { // The circuit breaker is Open. ... (see code sample below for details) } // The circuit breaker is Closed, execute the action. try { action(); } catch (Exception ex) { // If an exception still occurs here, simply // re-trip the breaker immediately. this.TrackException(ex); // Throw the exception so that the caller can tell // the type of exception that was thrown. throw; } } private void TrackException(Exception ex) { // For simplicity in this example, open the circuit breaker on the first exception. // In reality this would be more complex. A certain type of exception, such as one // that indicates a service is offline, might trip the circuit breaker immediately. // Alternatively it may count exceptions locally or across multiple instances and // use this value over time, or the exception/success ratio based on the exception // types, to open the circuit breaker. this.stateStore.Trip(ex); } }
The following example shows the code (omitted from the previous example) that is executed if the circuit breaker is not closed. It first checks if the circuit breaker has been open for a period longer than the time specified by the local OpenToHalfOpenWaitTime field in the CircuitBreaker class. If this is the case, the ExecuteAction method sets the circuit breaker to half-open, then attempts to perform the operation specified by the Action delegate.
下面的例子顯示了當電路斷路器沒有關閉時執行的代碼(略)。它首先檢查斷路器已開放了一段比在斷路器類的地方OpenToHalfOpenWaitTime字段中指定的時間更長。如果是這樣的話,那executeaction方法設置斷路器開一半,然后試圖執行的Action委托指定的操作。
If the operation is successful, the circuit breaker is reset to the closed state. If the operation fails, it is tripped back to the open state and the time at which the exception occurred is updated so that the circuit breaker will wait for a further period before attempting to perform the operation again.
如果操作成功,斷路器被重置為封閉狀態。如果操作失敗,則返回打開狀態,并將異常發生的時間更新,以便斷路器將等待進一步的時間,然后再進行操作。
If the circuit breaker has only been open for a short time, less than the OpenToHalfOpenWaitTime value, the ExecuteAction method simply throws a CircuitBreakerOpenException exception and returns the error that caused the circuit breaker to transition to the open state.
如果斷路器只開放很短的時間,比OpenToHalfOpenWaitTime價值的ExecuteAction方法只是拋出一個CircuitBreakerOpenException異常并返回導致斷路器的開啟狀態轉換誤差。
Additionally, to prevent the circuit breaker from attempting to perform concurrent calls to the operation while it is half-open, it uses a lock. A concurrent attempt to invoke the operation will be handled as if the circuit breaker was open, and it will fail with an exception as described later.
此外,為了防止斷路器在半開的時候,試圖對其進行并發調用,它使用了一個鎖。如果斷路器打開,將操作的并發嘗試操作將被處理,并且它將在稍后描述的情況下失敗。
... if (IsOpen) { // The circuit breaker is Open. Check if the Open timeout has expired. // If it has, set the state to HalfOpen. Another approach may be to simply // check for the HalfOpen state that had be set by some other operation. if (stateStore.LastStateChangedDateUtc + OpenToHalfOpenWaitTime < DateTime.UtcNow) { // The Open timeout has expired. Allow one operation to execute. Note that, in // this example, the circuit breaker is simply set to HalfOpen after being // in the Open state for some period of time. An alternative would be to set // this using some other approach such as a timer, test method, manually, and // so on, and simply check the state here to determine how to handle execution // of the action. // Limit the number of threads to be executed when the breaker is HalfOpen. // An alternative would be to use a more complex approach to determine which // threads or how many are allowed to execute, or to execute a simple test // method instead. bool lockTaken = false; try { Monitor.TryEnter(halfOpenSyncObject, ref lockTaken) if (lockTaken) { // Set the circuit breaker state to HalfOpen. stateStore.HalfOpen(); // Attempt the operation. action(); // If this action succeeds, reset the state and allow other operations. // In reality, instead of immediately returning to the Open state, a counter // here would record the number of successful operations and return the // circuit breaker to the Open state only after a specified number succeed. this.stateStore.Reset(); return; } catch (Exception ex) { // If there is still an exception, trip the breaker again immediately. this.stateStore.Trip(ex); // Throw the exception so that the caller knows which exception occurred. throw; } finally { if (lockTaken) { Monitor.Exit(halfOpenSyncObject); } } } } // The Open timeout has not yet expired. Throw a CircuitBreakerOpen exception to // inform the caller that the caller that the call was not actually attempted, // and return the most recent exception received. throw new CircuitBreakerOpenException(stateStore.LastException); } ...
To use a CircuitBreaker object to protect an operation, an application creates an instance of the CircuitBreaker class and invokes the ExecuteAction method, specifying the operation to be performed as the parameter. The application should be prepared to catch the CircuitBreakerOpenException exception if the operation fails because the circuit breaker is open. The following code shows an example:
使用斷路器保護對象的操作,應用程序創建的CircuitBreaker 的實例并調用ExecuteAction 方法,指定要執行的操作的參數。應用程序應該做好準備,因為如果斷路器打開操作失敗趕上CircuitBreakerOpenException 例外。下面的代碼顯示了一個示例:
var breaker = new CircuitBreaker(); try { breaker.ExecuteAction(() => { // Operation protected by the circuit breaker. ... }); } catch (CircuitBreakerOpenException ex) { // Perform some different action when the breaker is open. // Last exception details are in the inner exception. ... } catch (Exception ex) { ... }
Related Patterns and Guidance 相關模式和指導
•Retry Pattern. The Retry pattern is a useful adjunct to the Circuit Breaker pattern. It describes how an application can handle anticipated temporary failures when it attempts to connect to a service or network resource by transparently retrying an operation that has previously failed in the expectation that the cause of the failure is transient.
•Health Endpoint Monitoring Pattern. A circuit breaker may be able to test the health of a service by sending a request to an endpoint exposed by the service. The service should return information indicating its status.
重試模式。重試模式是斷路器模式的一個有用的輔助工具。它描述了應用程序如何處理預期的暫時的失敗時,它試圖連接到一個服務或重試操作,透明曾期望失敗的原因是短暫的失敗的網絡資源。
健康端點監測模式。斷路器可以通過發送一個請求來測試一個服務的健康狀況,該電路斷路器可以通過發送一個請求來測試該服務的健康狀況。該服務應返回指示其狀態的信息。
文章列表