preface

In a blog post on to introduce the usage of Eureka (great wisdom teach you Spring Cloud core components | first article: Eureka), may be after see friend thought, that if I were in access to the registry of a method, this method is not available? What if there are cascading failures (avalanche effects)? That’s where Hystrix comes in.

What is a circuit breaker?

Hystrix is a system to deal with distributed delay, and fault tolerance of the open source library, in a distributed system, many rely on will inevitably call fails, such as overtime, abnormal, Hystrix can guarantee in the case of a dependency problems, will not lead to the overall service failure, avoid cascading failure, in order to improve the flexibility of a distributed system. (Above content from Baidu)

When a service unit after failure occurs, through the circuit breaker fault monitoring, returned to the caller a in line with expectations, can deal with alternative response (Fallback), rather than waiting for a long time, or throw the caller can’t handle the exception, this is to ensure that the service of the caller thread will not be long, unnecessarily, This avoids the spread of failures in distributed systems and even avalanches.

A Hystrix is a circuit breaker.

Suppose you want to light A light bulb A (comparing the service to the light bulb), and you say to the current (comparing the current to the corresponding request) : you guys go find light bulb A and light it for me!

When the current receives your command, it carries a backpack and lights the bulb. Halfway through, the current finds that the switch in front of it is not closed (the circuit breaker is in effect) and the current can’t go through.

So the electricity asked, Brother, can’t we get through?

Switch (breaker) : Light bulb A is broken, this way is blocked, go back and tell the host that the road is blocked (” the road is blocked “is an expected and manageable alternative response), and let you go tomorrow when the light bulb is fixed.

The electric current will come back to tell you: this road can not go, have to change the route…

That’s when you know it’s not going to work, that light bulb A isn’t going to work, so you can start thinking of something else instead of just waiting for light bulb A to come on.

After reading this story, can we understand the circuit breaker more simply? The following code, through the code for you to explain the circuit breaker.

The circuit breaker

Let’s reopen the projects we created in the previous blog (Eureka-Server Service registry, Eureka-Client, Eureka-Consumer) and start these projects (this time we only need to start one Client). Eureka-client and Eureka-Consumer are registered in the eureka-Server service registry.If we access the address of the consumer, we can see that the method can be requested normally.Here’s a small change to the consumer code… The first step is to add a dependency to the POM.xml file

<! --hystrix--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>Copy the code

Then we’ll modify the startup class a little bit

package com.consumer1.consumer1;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;

import java.util.Map;

@RestController
@EnableEurekaClient
@SpringBootApplication
@EnableHystrix
public class Consumer1Application {

    @Autowired
    RestTemplate restTemplate;

    public static void main(String[] args) {
        SpringApplication.run(Consumer1Application.class, args);
    }

    /** * Instantiate RestTemplate *@return* /
    @LoadBalanced
    @Bean
    public RestTemplate rest(a) {
        return new RestTemplate();
    }

    /** * Use RestTemplate to make an HTTP request and get the data back to the front end *@param id
     * @return* /
    @HystrixCommand(fallbackMethod = "hiError")
    @GetMapping(value = "/request")
    @ResponseBody
    public Map<String,Object> getUser(@RequestParam Integer id){
        Map<String,Object> data = new HashMap<>();
        RestTemplate restTemplate = rest();
        data = restTemplate.getForObject("http://service-provider/getUser? id="+id,Map.class);
        return data;
    }
    
    public Map<String,Object> hiError(Integer id) {
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("message"."Mistake!!");
        returnmap; }}Copy the code

We have made three changes. The first is to add an @enablehystrix annotation to the bootstrap class to enable circuit breakers. The second is to add a @hystrixCommand (fallbackMethod = “hiError”) annotation to the getUser method to create a fuse function for the method. FallbackMethod (hiError); fallbackMethod (hiError); fallbackMethod (hiError); The third is the addition of a hiError fuse method.

Note that the @hystrixCommand (fallbackMethod = “XXX”) method must have the same parameter and return type as the XXX method, that is, the Hystrix method and the exception method must be identical

If the eureka-client is stopped, it will say “this website cannot be accessed” when it attempts to access the Client address.So what if we access the consumer’s address, see if the circuit breaker works?We can see that the circuit breaker is in effect. Because the client is stopped, an exception occurs when the client accesses the corresponding method, which executes the fallbackMethod fusing method and returns an error message, instead of waiting for the response to timeout, which controls the thread blocking of the container.

conclusion

In distributed systems, the unavailability of an underlying service often leads to the unavailability of the entire system, also known as the service avalanche effect. Manual downgrading is a common way to deal with service avalanches, and Hystrix gives us an alternative.

My experience is limited, some places may not be particularly in place, if you think of any questions when reading, welcome to leave a message in the comments section, we will discuss one by one 🙇

Please take a thumbs up and a follow (✿◡‿◡) for this article ~ a crab (●’◡’●)

If there are mistakes in the article, welcome to comment correction; If you have a better, more unique understanding, you are welcome to leave your valuable ideas in the comments area.

Love what you love, do what you do, listen to your heart and ask nothing