springcloud (ten): Hystrix workflow analysis

Flowchart Netflix Hystrix official announcement, we look at Hystrix workflow

 

1. Create HystrixCommand object or objects HystrixObservableCommand

First create a HystrixCommand HystrixObservableCommand object or objects used to represent the dependence of the operation request and services, while passing all the necessary parameters, it uses the command mode to achieve encapsulation of the service call operation, the two Command objects for each different application scenarios .

  • HystrixCommand: dependent services each return a single response.
HystrixCommand command = new HystrixCommand(arg1, arg2);
  • HystrixObservableCommand: If desired depend on service returns an Observable, and apply the Observer pattern monitor dependent services respond, with return multiple operating result in time-dependent services.
HystrixObservableCommand command = new HystrixObservableCommand(arg1, arg2);



Command Mode

Of the command mode, the request is encapsulated as an object, using different requests, the queue, logs or other objects is parameterized request, is the command mode. Command mode can also support undo. When objects need to request the execution request of the object and decoupled, consider command mode.

For example, what is the command, a command is to turn on the light for example, we can name LightOnCommand this command, the above said object encapsulates the request into a turn on the light of this means is that the request (command), encapsulated LightOnCommand this subject, but this certainly does not own LightOnCommand command execution, to determine who is to be executed this command, this command is executed while the object is light, then you can put this light, such as energy-saving lamps CellingLight objects injected into the command , added LightOnCommand a command object execute () method, operable to perform light.on () (turn on the light) is. It says the command object, the performers (who were ordered or called) objects objects, there is still an executive order, here is a remote control, the LightOnCommand objects injected in, when executing the command, we can directly call this command objects just fine without knowing my command in the end this is what a specific light to carry, so that to achieve a decoupling of the program. Of course, apart from the presence execute () method as a method of operation of the next execution, you can also provide a undo () method revocation.

 Command Mode of points:

  1. Command mode will issue the requested object and the object execution request decoupling;
  2. In between the two is decoupled to communicate through the command object. Command objects encapsulate or receiver and a set of actions;
  3. The caller request by invoking the command object execute () method, which would make the operation of the receiver is called;
  4. The caller can accept commands as arguments, even dynamically at runtime;
  5. Commands can support undo, the practice is to achieve a undo () method to return to execute () method is executed before the state;

 

Command execution

We saw a total of four named implementation from the figure, which HystrixCommand achieve the implementation of these four, but mainly use the first two:

  • execute (): synchronous execution and returns a single result object from the dependent services, or throw an exception when the error occurred.
  • queue (): asynchronous execution, direct returns a Future object that contains a single result object at the end of service execution to return.
  1. R value = command.execute();
  2. Future<R> fValue = command.queue();

HystrixObservableCommand achieved two other implementation.

  • observe (): returns Observable object returns Observable object request immediately, dependent upon the service response (or throw an exception / out), obtained by the Subscriber registration return result, it is a Hot Observable.
  • toObservable (): return Observable object, but the object only when the subscription is issued until the request, and then rely on the service response (or throw an exception / overtime), by registered Subscriber been returned result, it is a Cold Observable.
  1. Observable<R> ohValue = command.observe(); //hot observable
  2. Observable<R> ocValue = command.toObservable(); //cold observable

Extensive use of RxJava in the underlying implementation Hystrix in, here's a brief observer RxJava - mode subscribers.

Observable object can be understood as an event source or viewer, that the Subscriber corresponding objects can be understood as the subscriber or viewer.

  1. Observable used to publish events to subscribers Subscriber objects, Subscriber objects are handled after it receives an event, the event referred to here is the call to depend on the service.
  2. A Observable object can send multiple events until the end of, or exception occurs.
  3. Observable each object emits an event that will call the corresponding observer Subscriber object onNext () method.
  4. Observable perform each of the last will by calling Subscriber.onCompleted () or Subscriber.onError () to end the operation flow of the event.

The following is a simple example

 1 public static void main(String[] args) {
 2         //创建被观察者/事件源observable
 3         Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
 4             
 5             @Override
 6             public void call(Subscriber<? super String> subscriber) {
 7                 // TODO Auto-generated method stub
 8                 subscriber.onNext("hello!RxJava");
 9                 subscriber.onNext("hello!Spring Cloud Hystrix");
10                 subscriber.onCompleted();
11             }
12         });
13         
14         //创建观察者/订阅者subscriber
15         Subscriber<String> subscriber = new Subscriber<String>(){
16  
17             @Override
18             public void onCompleted() {
19                 // TODO Auto-generated method stub
20                 System.out.println("success");
21             }
22  
23             @Override
24             public void onError(Throwable e) {
25                 // TODO Auto-generated method stub
26                 System.out.println("fail");
27             }
28  
29             @Override
30             public void onNext(String t) {
31                 // TODO Auto-generated method stub
32                 System.out.println(t);
33             }
34             
35         };
36         observable.subscribe(subscriber);
37 }

In this example, we create a simple event source observable, a subscriber to the event delivery content output subscriber, to trigger release event by observable.subscribe (subscriber).

About Hot Observable and Cold Observable, which Hot Observable event regardless of whether the source of the event has subscribers will be published after it is created, so for Hot Observable each subscriber are likely to start from the middle of the event source, and the only see the whole operation of the local process; and Cold Observable not be released in the absence of the subscriber's event, but to wait until the event was released after subscribers, so for Cold Observable subscribers, it can be guaranteed from the outset see the whole process of the whole operation.

In fact more than observe () and toObservable () uses RxJava, execute () and queue () also use RxJava to achieve.

 1 public R execute() {
 2      try {
 3          return queue().get();
 4      } catch (Exception e) {
 5          throw Exceptions.sneakyThrow(decomposeException(e));
 6      }
 7 }
 8 //
 9  
10 public Future<R> queue() {
11         
12       final Future<R> delegate = toObservable().toBlocking().toFuture();
13         
14       final Future<R> f = new Future<R>() {
15         ...
16             
17       };
18  
19       if (f.isDone()) {
20           try {
21               f.get();
22               return f;
23           } catch (Exception e) {
24               ... 
25           }
26       }
27       return f;
28 }
  • execute () by Queue () Returns the target asynchronous Future <R> of the get () method to achieve synchronization is performed. This method will wait for the end of the task execution, and the result obtained is returned R type.
  • Queue () is () obtained by a toObservable Cold Observable, and () into the Observable BlockingObservable by toBlocking, which data can be emitted in a blocking manner. The toFuture method is to convert BlockingObservable to Future, the only method to create a Future returns will not be blocked, which makes consumers can decide for themselves how to handle the asynchronous operation. The execute () is the direct use of the queue () method obstruction Future returned by the get () to achieve synchronous operation. Simultaneously switched in this way only a Future requirements Observable transmit data, so the two can only return a single result achieved.

 

3. whether the results are cached

If the request caching feature of the current command is enabled, and the command cache hit, then the cached results are returned immediately in the form of Observable object.

4. The circuit breaker is open

Whether at the time the command is not the result of a cache hit, Hystrix checks before executing the command circuit breaker is open

  • If the circuit breaker is open, it will not execute the command Hystrix, but transferred to the fallback processing logic (step 8).
  • If the circuit breaker is off, Hystrix will check for available resources to execute the command (step 5).

 

 

 

The thread pool, the request queues, semaphores whether filled

If the thread pool associated with the command or request queues and semaphores (thread pool when not in use) has been filled, it will not execute the command Hystrix, but transferred to the fallback processing logic (step 8). Note that this is not a container thread pool thread pool but Hystrix order to ensure that does not affect service because of a dependency problems to other dependent services and the use of the "bulkhead mode" to isolate each dependent services.

6.HystrixObservableCommand.construct()或HystrixCommand.run()

Hystrix will decide what way to take a request dependent services according to the way we write.

  • HystrixCommand.run () - returns a single response or throw an exception.
  • HystrixObservableCommand.construct () - Returns the object to transmit a plurality Observable results or error notification sent by onError.

If the run () or construct () method executes when the command is longer than the timeout threshold, its thread will throw a TimeoutException (or throw in a separate thread, if the command does not run in its own thread). In this case transferred to the fallback processing logic Hystrix (step 8). And if the command does not cancel or interrupt, it will give up the run () or construct () method returns the final value.

If the command does not throw an exception and returns a response, Hystrix will return the results to the caller after the execution of some logs and metrics reporting. If it was run () operation, the return Observable MAMMALIA, transmitting a single result, and then sends a notification onCompleted; if it is running through the construct, the process returns directly MAMMALIA, produced () Observable object.

7. Calculate the health of the circuit breaker

Hystrix will be success, failure, rejection, overtime and other information reported to the breaker, breaker and maintains a set of counters to count the data. Breaker will use this data to determine whether the circuit breaker to open, to fuse, short circuit relies on a service request, until the end of the recovery period, if after the end of the recovery period, according to statistics judge has not yet reached the health indicators, will blow again , a short-circuit.

8.fallback processing

When the command fails, Hystrix will enter fallback attempt to roll back process, also known as service degradation, request service degradation may be introduced are the following categories:

  1. Step 4, the current command is blown, a short circuit state, when the circuit breaker is open.
  2. Step 5, the current command thread pool, the request queues, semaphores when being filled.
  3. Step 6, HystrixObservableCommand.construct () or HystrixCommand.run () when throwing an exception.

Logic in service degradation, the need to achieve a common response result, and the processing logic of the results should be acquired in accordance with some or static logic from the cache, rather than relying on the network request to obtain, if included in the service must be degraded logic network request, the request must be packaged in or HystrixObservableCommand HystrixCommand, thereby forming a cascade of strategy degraded, and the final degraded logic must not rely on a process network requests, but can be a stable processing logic returns the results.

  1. In HystrixCommand provided callback custom logic HystrixCommand.getFallback () method, the callback method returns a single value.
  2. In HystrixObservableCommand provided callback custom logic HystrixObservableCommand.resumeWithFallback () method, a method returns Observable object to transmit one or more degraded results.

When downgrading logical command returns the result, Hystrix on the result returned to the caller. When using HystrixCommand.getFallback (), which returns a Observable object that emits getFallback () processing result. The use HystrixObservableCommand.resumeWithFallback () will return directly when Observable object implementation.

If there is no logic to achieve downgrade or downgrade logic command throws an exception, Hystrix still returns an Observable object, but it does not emit any results data, but by notification command onError method immediately interrupt request, and by onError () method the anomaly is sent to the caller, we should try to avoid relegation case of a failure occur. If you downgrade policy logic execution failure occurs, Hystrix will make the following processes according to different modes of implementation:

  1. execute () - an exception is thrown
  2. queue () - Returns the java.util.concurrent.Future success, but if you call Future.get () will throw an exception
  3. observe () - Returns the Observable object when you subscribe to the Observable, it will be terminated immediately and call the method subscribers onError
  4. toObservable()——同observe()

9. Return successful response

When the command is executed successfully Hystrix, a processing result will be returned directly or in the form of Observable returns, returns to how to distinguish specific embodiment according to the execution command, the four kinds of dependencies is performed FIG manner:

  1. execute (): and queue () Gets a Future obtain the same way, and then block and wait for the result by calling the get () method returns.
  2. queue (): The original Observable toObservable () produced by the method of converting toBlocking () into BlockingObservable object and call its toFuture () method returns the asynchronous Future object.
  3. observe (): subscription after the generation of the original Observable in toObservable () it immediately, so that commands can immediately start asynchronous execution, and returns an Observable object when calling its subscribe, will again produce results and notifications to subscribers.
  4. toObservable (): Returns the most primitive Observable, users must subscribe to the subscription process it can really begin to execute the command.

---------------------
Author: myCat,
Source: CSDN
Original: https: //blog.csdn.net/WYA1993/article/details/82152597
Copyright: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/holly8/p/11226177.html