Deep into Hystrix Circuit Breaker Implementation Principle One Point Classroom (Multi-shore College)

Posted by stuartbaggs on Tue, 03 Sep 2019 13:56:44 +0200

RequestVolumeThreshold

HystrixCommandProperties.Setter()
    .withCircuitBreakerRequestVolumeThreshold(int)

Represents how many requests in a sliding window may trigger a circuit break.

Only when the flow of Hystrix through the circuit breaker exceeds a certain threshold can it be possible to trigger the circuit break. For example, it is required that the flow through the circuit breaker must reach 20 in 10 seconds, while the actual flow through the circuit breaker is only 10, so it is not necessary to judge whether to open the circuit at all.

ErrorThresholdPercentage

HystrixCommandProperties.Setter()
    .withCircuitBreakerErrorThresholdPercentage(int)

The default value is 50 (%).

If the proportion of abnormal calls counted by the circuit breaker exceeds a certain threshold, for example, within 10 seconds, the flow through the circuit breaker reaches 30, and the number of abnormal calls reaches a certain proportion, such as 60% of requests are abnormal (error/timeout/reject), the circuit breaker will be opened.

SleepWindowInMilliseconds

HystrixCommandProperties.Setter()
    .withCircuitBreakerSleepWindowInMilliseconds(int)

Opening of a circuit breaker is the transition from close to open (close-> open). Then in the Sleep Windows In Milliseconds time, all requests passing through the circuit breaker will be disconnected, without calling back-end services, and go directly to fallback degrading mechanism.

After this parameter time, the circuit breaker will change to half-open half-open half-closed state, trying to let a request pass through the circuit breaker to see if it can be normally invoked. If the call is successful, it will be automatically restored and the circuit breaker will be closed.

Enabled

HystrixCommandProperties.Setter()
    .withCircuitBreakerEnabled(boolean)

Controls whether circuit breakers are allowed to work, including tracking the health of dependent service invocations, and whether triggered circuit breaks are allowed when there are too many exceptions. The default value is true.

ForceOpen

HystrixCommandProperties.Setter()
    .withCircuitBreakerForceOpen(boolean)

If set to true, the direct force to open the circuit breaker is equivalent to manual circuit breaker, manual downgrade, the default value is false.

ForceClosed

HystrixCommandProperties.Setter()
    .withCircuitBreakerForceClosed(boolean)

If set to true, direct forced closure of the circuit breaker, equivalent to manual stop the circuit breaker, manual upgrade, the default value is false.

Example Demo

HystrixCommand configuration parameters

Configure Setter circuit breaker parameters in GetProduct InfoCommand.

  • In a sliding window, at least 20 requests may trigger a circuit break.
  • When the abnormal proportion reaches 40%, the circuit break will be triggered.
  • Within 3000ms after the circuit break, all requests are reject ed and downgraded directly by fallback without calling the run() method. After 3000ms, it becomes half-open.

In the run() method, let's determine whether productId is - 1, and if so, throw an exception directly. In this way, we can pass in productId=-1 when we test later to simulate the service execution exception.

In the degrading logic, we just return the degraded goods to it directly.

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()
                        // Is Circuit Breaker Allowed to Work
                        .withCircuitBreakerEnabled(true)
                        // How many requests are there in a sliding window to trigger a circuit break?
                        .withCircuitBreakerRequestVolumeThreshold(20)
                        // When the abnormal ratio reaches 50%, the open circuit will be triggered by default.
                        .withCircuitBreakerErrorThresholdPercentage(40)
                        // How long does the reject request occur directly after the circuit break, and then enter the half-open state, default 5000ms
                        .withCircuitBreakerSleepWindowInMilliseconds(3000)));
        this.productId = productId;
    }

    @Override
    protected ProductInfo run() throws Exception {
        System.out.println("Invoke interface to query commodity data. 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("Degraded commodities");
        return productInfo;
    }
}

Circuit Breaking Test Class

In our test class, the first 30 requests are passed in productId=-1, then dormant for 3 seconds, and then 70 requests are passed in 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) {
            // Input - 1, throws an exception, and then goes down the degrade logic
            HttpClientUtils.sendGetRequest(baseURL + "-1");
        }

        TimeUtils.sleep(3);
        System.out.println("After sleeping...");

        for (int i = 31; i < 100; ++i) {
            // Input 1, normal call of service
            HttpClientUtils.sendGetRequest(baseURL + "1");
        }
    }
}

test result

From the test results, we can clearly see the whole process of system breaking and recovery.

Invoke interface to query commodity data, productId=-1
 Product Info (id = null, name = degraded goods, price=null, pictureList=null, specification=null, service=null, color=null, size=null, shopId=null, modifiedTime=null, cityId=null, cityName=null, brandId=null, brandName=null)
// ...
// Here, the results are printed 20 times over.


Product Info (id = null, name = degraded goods, price=null, pictureList=null, specification=null, service=null, color=null, size=null, shopId=null, modifiedTime=null, cityId=null, cityName=null, brandId=null, brandName=null)
// ...
// Here the results are printed eight times over.


// After 3 seconds of dormancy
 Invoke interface to query commodity data, productId=1
 Product Info (id = 1, name = iPhone 7, price = 5599.0, pictureList = a.jpg, b.jpg, specification = iPhone 7 specifications, service = iPhone 7 after-sales service, color = red, white, black, size = 5.5, shopId = 1, modified time = 2017-01-12:00:00, cityId = 1, yName = null, Id = 1, brandme = null)
// ...
// The results are reprinted 69 times.

For the first 30 requests, we passed in a productId of - 1, so an exception is thrown during service execution. We set up at least 20 requests to go through the circuit breaker and trigger the circuit break when the abnormal ratio exceeds 40%. Therefore, 21 interface calls were executed, each time an exception was thrown and the circuit breaker was turned on after 21 calls.

The following nine requests do not execute the run() method, nor do they print the following information.

Invoke interface to query commodity data, productId=-1

Instead, go straight to the downgrade logic and call getFallback() to execute.

After sleeping for 3 seconds, we passed in productId for 1 in the next 70 requests. Since we set up 3000ms before, the circuit breaker becomes half-open. So Hystrix tries to execute the request and finds that it succeeds, then the circuit breaker closes and all subsequent requests can be invoked properly.

Thank you for seeing it. If you can help me, please give me a compliment.

More experience and technology are welcome to come and learn together.
A little Classroom - Online Learning Platform for Dreams http://www.yidiankt.com/

[Pay attention to the public number and get it free of charge -[java Core Knowledge Points]

QQ discussion group: 616683098
Students who want to study in depth can join the QQ group discussion, have a full set of resources to share, experience to discuss, yes, we are waiting for you to share each other's stories!

Topics: Windows Java