如何在java中实现Load Balancer

时间:2017-04-10 05:53:38

标签: java load-balancing netflix-eureka hystrix spring-cloud-netflix

我希望实现一种模式,如果错误百分比超过阈值,该模式会自动或手动停止对外部服务(即端口)的所有请求一段时间。我有两个服务器实例在不同端口的同一台机器上运行(例如:2401,2402)。

现在的要求是,如果端口2401超过了错误百分比阈值,那么我想停止对该端口(2401)的所有请求一段时间并路由到另一个端口(2402)。哪种算法适合我,我不确定。

我阅读了一些文章,但没有获得有关Java代码中Load Balancer实现的完整信息。

提前致谢, Sateesh

1 个答案:

答案 0 :(得分:1)

@Svetlin完全正确,你可以用hystrix实现这一点。这是一个示例代码。根据您的要求进行调整。

    @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的请求失败时,计数器会递增,并且调用将转到fallback方法(fallBackForProductDetail)并在fallback方法中执行代码。相同的行为一直持续到达到阈值(在这种情况下为5)。达到阈值后,控件甚至不进入main方法(callProductDetail),它直接进入回退方法。这种情况发生在sleepWindowInMilliseconds(在这种情况下为20分钟)。

希望它有所帮助。