@Svetlin是完全正確的,你可以用紅椎實現這一目標。這是一個示例代碼。適應您的要求。
@HystrixCommand(fallbackMethod = "fallBackForProductDetail", groupKey = "CircuitBreaker", commandKey = "frontend-productdetail", threadPoolKey = "frontend-productdetail",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),//Time before which this call is supposed to complete. if not throw exception. this is Optional
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "5"), // Number of requests before which the cicuit is open
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1200000"),//20 minutes circuit will be open
},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "30"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "180000")// 3 minutes rolling window. i.e the errors calculated for every 3 minute window.
})
public String callProductDetail(.....){
// call server1
}
// Return type and arguments should be exactly same as the method for wich this is fallback. (With an optional Throwable argument to catch exception)
public String fallBackForProductDetail(...){
// call server2
}
現在來解釋行爲。當對server1的請求失敗時,計數器遞增,並且調用進入回退方法(fallBackForProductDetail)並在回退方法內執行代碼。同樣的行爲會持續到達到閾值(在這種情況下爲5)。達到閾值後,控件甚至不會進入main方法(callProductDetail),它直接進入回退方法。這發生在sleepWindowInMilliseconds
(在這種情況下爲20分鐘)。
希望它有幫助。
看看Hystrix的CircuitBreaker impl(hystrix命令)。您不需要LB –
但是,當我們將斷路器應用於某個方法時,Hystrix會監視該方法的失敗呼叫,並且如果失敗達到閾值,Hystrix將打開該電路,以便後續呼叫自動失敗。這個鍛鍊我不確定。 –
您可以覆蓋「getFallback」方法,然後可以使用其他命令調用第二個服務實例。 –