1

我想實現一種自動或手動的模式,以便在錯誤百分比超過閾值時停止一段時間內對外部服務(即端口)的所有請求。我有兩個服務器實例在不同端口的同一臺計算機上運行(例如:2401,2402)。如何在java中實現負載均衡器

現在的要求是,如果端口2401通過錯誤百分比閾值,那麼我想在一段時間內停止對此端口(2401)的所有請求並路由到另一個端口(2402)。哪個算法適合這個我不確定。

我閱讀了一些文章,但沒有在Java代碼中獲得關於Load Balancer實現的完整信息。

由於提前, Sateesh

+0

看看Hystrix的CircuitBreaker impl(hystrix命令)。您不需要LB –

+0

但是,當我們將斷路器應用於某個方法時,Hystrix會監視該方法的失敗呼叫,並且如果失敗達到閾值,Hystrix將打開該電路,以便後續呼叫自動失敗。這個鍛鍊我不確定。 –

+0

您可以覆蓋「getFallback」方法,然後可以使用其他命令調用第二個服務實例。 –

回答

1

@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分鐘)。

希望它有幫助。

+0

非常感謝@pvpkiran的幫助。 –

+0

很高興幫助。如果它有用,請投票。 – pvpkiran

+0

現在擔心我會upvote): –