有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中实现负载均衡器

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

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

我读了一些文章,但没有读到关于Java代码中负载平衡器实现的完整信息

提前谢谢, 萨蒂什


共 (1) 个答案

  1. # 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),而是直接进入fallback方法。这种情况会持续sleepWindowInMilliseconds(本例中为20分钟)

    希望有帮助