You might be asked in an interview if you’ve ever used Hystrix and how he did it. If you say, “I configured the fuse to turn on in my profile, and then marked the interface method with the fuse @hystrixCommand, congratulations.” It must be “GG.”

Now let’s talk about what Hystrix can do and how it works.

advantages

1 Service degradation circuit breaker

2 Thread signal isolation

3 Request caching Request merging and service monitoring

As usual, start a project, enter a door, start the Hello-server service through port 8081 and port 8082, and then start a ribbon-consumer service

/** * Start the ribbon- Consumer service and enable a fuse with EnableCircuitBreaker * EnableDiscoveryClient register with the registry /** @enablecircuitbreaker @EnableDiscoveryClient @SpringBootApplication public class ConsumerApplication { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code

And just for the record, there’s another annotation that you can use instead which is @SpringCloudApplication and what’s inside it is

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public @interface SpringCloudApplication {
}
Copy the code

We see that the above annotation is included, and then access eruka

How can a service be started twice on IDEA via different ports

We first add a service in IDEA, select the main class to load, and configure the port number, and then start it

Then we visit http://localhost:9000/ribbon-consumer

With the result of the interface returned, take a look at the interface code

  @HystrixCommand(fallbackMethod = "helloFallback", commandKey = "helloKey")
    public String hello() {
        long start = System.currentTimeMillis();

        StringBuilder result = new StringBuilder();

        // GET
        result.append(restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody()).append("<br>");
        }
   }
   public String helloFallback() {
        return "error";
    }         
Copy the code

We see that this method accesses the Hello-service, so we close the hello-service and try again

At this point, we see that the result is the “error” returned by the specified demote method helloFallback().

Let’s take a look at how he works

We see that the workflow starts with the two HystrixCommand and HystrixObservableCommand classes. Think about the fuse that Hystrix implements. How does the monitoring function relate to these two classes?

We found that both classes have a Command in common, and that Command is at the heart of Hystrix, which is that it actually uses the Command pattern.

Command mode is one of the design modes, we often say that we can not use design mode, in fact, look at the source code, itself is to learn the design mode, then let’s see what command mode is used to do, first look at a picture

And then look at the code

public class CommandPattern { public static void main(String[] args) { Receiver receiver = new Receiver() Command cmd = new ConcreteCommand(receiver); Invoker ir = new Invoker(cmd); System.out.println(" Customer access to caller's call() method..." ); ir.call(); }} class Invoker {private Command Command; public Invoker(Command command) { this.command = command; } public void setCommand(Command command) { this.command = command; } public void call() {system.out.println ("... ); command.execute(); } // Interface Command {void execute(); } class ConcreteCommand implements Command {private Receiver Receiver; ConcreteCommand(Receiver receiver) { this.receiver = receiver; } public void execute() { receiver.action(); Public void action() {system.out.println (" The Receiver's action() method is called..." ); }}Copy the code

Command mode is quite simple, actually is to the caller and receiver with a middle tier, isolated, so as to achieve the aim of decoupling, and at the same time of decoupling, we can in order to add some we want to do, and intermediate command mode is abstract, so we can choose different command implementation to do different things.

Simply put, the command pattern consists of four parts: caller, receiver, abstract command, and implementation of the command (there may be more than one, you choose).

Hystrix has different command implementations such as callBack, request queuing, and command undo, so this command mode is at the heart of Hystrix.

Through the workflow diagram, we can see that Hystrix has two command classes, which correspond to two execution modes respectively, and a total of four execution modes

excute,queue,oberve,toObservable.

All four ended up using RxJava’s responsive programming style.

Let’s go through the process

1 Create HystrixCommand and HystrixObservableCommand objects
2 command execution by excute, queue, oberve toObservable
3 Check whether request caching is enabled
4 check whether the circuit breaker is open. If so, fallback
5 Check whether the thread pool semaphore is full, if it is full fallback
6 Calculate the health of the circuit breaker
7 fallback process
8 Returns a successful response

This is how Hystrix works, and the basic idea of Hystrix. There are many other things about Hystrix. If you are interested in Hystrix, this article will be a good introduction