In-depth implementation of the principle of Hystrix breaker

Copyright: ~ reproduced please marked, thank you - if infringement please private letter to me, I will immediately delete ~ https://blog.csdn.net/baidu_26954625/article/details/90635574

本系列内容转载自git项目advancejava

RequestVolumeThreshold

HystrixCommandProperties.Setter().withCircuitBreakerRequestVolumeThreshold(int)

Said in a sliding window, there is at least the number of requests, it may trigger disconnection.
Hystrix flow through the circuit breaker exceeds a certain threshold value, will it be possible to trigger disconnection. For example, requiring flow through the circuit breaker must be reached 20 in the 10s, while the actual flow through the circuit breaker was 10, I would not have to judge whether or not to break.

ErrorThresholdPercentage

HystrixCommandProperties.Setter().withCircuitBreakerErrorThresholdPercentage(int)

Indicating an abnormal proportion of how much to trigger circuit, the default value is 50 (%).
If the circuit breaker statistics to the proportion of abnormal calls exceeds a certain threshold, for example, in the 10s, the flow through the circuit breaker has reached 30, while the number of anomalies which access has reached a certain percentage, such as 60% requests are an exception (error / timeout / reject), will open circuit.

SleepWindowInMilliseconds

HystrixCommandProperties.Setter().withCircuitBreakerSleepWindowInMilliseconds(int)

Breaking open, which is converted by the close to the open state (close -> open). So after SleepWindowInMillisecondsa time, after all the requests will be open circuit breaker of all, do not call back-end service, go directly to downgrade fallback mechanism.
In the time after the argument, the breaker becomes half-open half-open closed, try to make a request through the circuit breaker, see if I can properly call. If the call is successful, then it is automatically restored, converted to close the circuit breaker status.

Enabled

HystrixCommandProperties.Setter().withCircuitBreakerEnabled(boolean)

Controls whether to allow the circuit breaker, including tracking service calls depend on health status, and whether to allow too much trigger disconnection of the abnormality. The default value is true.

ForceOpen

HystrixCommandProperties.Setter().withCircuitBreakerForceOpen(boolean)

If set to true, then forced open the circuit breaker directly, the equivalent of a handoff, manual downgrade, default value is false.

ForceClosed

HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(boolean)

If set to true, direct forcibly closed circuit breaker, which is equivalent to manually stop breaking the manual upgrade, the default value is false.

In the GetProductInfoCommandconfiguration Setter breaker associated parameter.
• sliding window, at least 20 requests, it may trigger disconnection.
• When an abnormal ratio of 40%, only trigger circuit.
• After the break within 3000ms, all requests are reject, go directly fallback downgrade, does not call the run () method. After 3000ms, it becomes a half-open state.
run () method, we determine what productIdif -1, yes, direct throw. So write, we can pass the test after productId=-1the abnormal simulation services performed.
In downgrade logic, we return it directly to the downgrade of goods just fine.

public class GetProductInfoCommand extends HystrixCommand<ProductInfo> {
private Long productId;
private static final HystrixCommandKey KEY = HystrixCommandKey.Factory.asKey("GetProductInfoCommand");
public GetProductInfoCommand(Long productId) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ProductInfoService"))
                .andCommandKey(KEY)
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        // 是否允许断路器工作
                        .withCircuitBreakerEnabled(true)
                        // 滑动窗口中,最少有多少个请求,才可能触发断路
                        .withCircuitBreakerRequestVolumeThreshold(20)
                        // 异常比例达到多少,才触发断路,默认50%
                        .withCircuitBreakerErrorThresholdPercentage(40)
                        // 断路后多少时间内直接reject请求,之后进入half-open状态,默认5000ms
                        .withCircuitBreakerSleepWindowInMilliseconds(3000)));
        this.productId = productId;
    }
@Override
    protected ProductInfo run() throws Exception {
        System.out.println("调用接口查询商品数据,productId=" + productId);
if (productId == -1L) {
            throw new Exception();
        }
String url = "http://localhost:8081/getProductInfo?productId=" + productId;
        String response = HttpClientUtils.sendGetRequest(url);
        return JSONObject.parseObject(response, ProductInfo.class);
    }
@Override
    protected ProductInfo getFallback() {
        ProductInfo productInfo = new ProductInfo();
        productInfo.setName("降级商品");
        return productInfo;
    }
}

Open test categories
we tested class, the first 30 requests, incoming productId=-1, and then sleep 3s, 70 times after the request, passed productId=1.

@SpringBootTest
@RunWith(SpringRunner.class)
public class CircuitBreakerTest {
@Test
    public void testCircuitBreaker() {
        String baseURL = "http://localhost:8080/getProductInfo?productId=";
for (int i = 0; i < 30; ++i) {
            // 传入-1,会抛出异常,然后走降级逻辑
            HttpClientUtils.sendGetRequest(baseURL + "-1");
        }
TimeUtils.sleep(3);
        System.out.println("After sleeping...");
for (int i = 31; i < 100; ++i) {
            // 传入1,走服务正常调用
            HttpClientUtils.sendGetRequest(baseURL + "1");
        }
    }
}

Test results
test results, we can clearly see that the whole system is breaking with the recovery process.
Call Interface product data query,productId=-1

ProductInfo(id=null, name=降级商品, price=null, pictureList=null, specification=null, service=null, color=null, size=null, shopId=null, modifiedTime=null, cityId=null, cityName=null, brandId=null, brandName=null)
// ...
// 这里重复打印了 20 次上面的结果
ProductInfo(id=null, name=降级商品, price=null, pictureList=null, specification=null, service=null, color=null, size=null, shopId=null, modifiedTime=null, cityId=null, cityName=null, brandId=null, brandName=null)
// ...
// 这里重复打印了 8 次上面的结果
// 休眠 3s 后
调用接口查询商品数据,productId=1
ProductInfo(id=1, name=iphone7手机, price=5599.0, pictureList=a.jpg,b.jpg, specification=iphone7的规格, service=iphone7的售后服务, color=红色,白色,黑色, size=5.5, shopId=1, modifiedTime=2017-01-01 12:00:00, cityId=1, cityName=null, brandId=1, brandName=null)
// ...
// 这里重复打印了 69 次上面的结果

30 times before requesting, we pass productIdto -1, the process execution service will throw an exception. We set up a minimum of 20 times a request by a circuit breaker and an abnormal ratio exceeding 40% on the trigger circuit. Therefore, the implementation of the interface calls 21 times, each time throwing an exception and go downgrade, after 21 times, the circuit breaker was opened.
After nine requests, will not perform the run () method, it will not print the following information.
Call Interface product data query, productId=-1
but go directly to downgrade logic, call getFallback()execution.
After a dormant 3s, we requested 70 times thereafter, both the incoming productIdone. Since we set up in front of the circuit breaker becomes 3000ms after half-open state. Therefore Hystrix will try to execute the request, find success, then turn off the circuit breaker, after all requests can be called normal.

Guess you like

Origin blog.csdn.net/baidu_26954625/article/details/90635574