Some applications and ideas of Hystrix and Application Ideas of Hystrix

Source: Internet
Author: User

Some applications and ideas of Hystrix and Application Ideas of Hystrix
1. Introduction to Hystrix

To be honest, with the top name of hystrix, its introduction is everywhere. The most accurate of course is the official, interested can take a look at its official wiki: https://github.com/Netflix/Hystrix/wiki

In a distributed environment, inevitably some of the specified service dependencies will fail. hystrix is a library that helps you control the interactions between these distributed services by adding latency tolerance and fault tolerance logic. hystrix does this by isolating points of access between the services, stopping cascading failures into SS them, and providing fallback options, all of which improve your system's overall resiliency.

In short, it is to enhance the Failover rate and error handling logic of a distributed system. By isolating dependency failures, hystrix reduces the latency of the entire service to a controllable range. That is to say, the response time of the entire service is controllable and will not greatly increase or even increase the response time of the entire service due to the delay or error of a dependent service or the high concurrency.

2. How does Hystrix address dependency isolation?

Hystrix is actually a set of command pattern (command mode) encapsulation, to understand the working principle of Hystrix first to understand command pattern, about command pattern can look at this: http://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/command.html

Hystrix is a bit different. It provides abstract command classes, but its abstract command classes provide four execution modes: execute (synchronous mode), queue (asynchronous execution ), observable (Reactive mode of immediate request) and toObservable (Reactive mode of request during subscription ).

  • Encapsulate the logic of all external request systems (or dependent services) into HystrixCommand or HystrixObservableCommand objects. These logics will be executed in independent threads.
  • Hystrix uses the automatic Timeout Policy (1000 ms by default ). This policy applies to all commands by default. You can also set the Command configuration to customize the timeout time. All default settings are shown in HystrixCommandProperties.
  • You can maintain a thread pool for each service. You can choose whether to wait or refuse when the thread is used up. The maximum length of the waiting queue is what, which greatly improves the controllability and flexibility of the dependent service, all thread pool configurations can be seen in HystrixThreadPoolProperties.
  • The default getExecutionException () method can be used to identify four types of exceptions that may occur when the request is successful, failed (throwing an exception), timed out, or the thread pool is full.
  • The "fuse" mechanism is introduced to manually or automatically cut off the service for a period of time when the dependent service failure ratio exceeds the threshold.
  • The fallback () method is executed when a request fails. Multiple requests (inheriting from HystrixCollapser) do not execute any subsequent requests but directly execute fallback.
  • Hystrix provides monitoring and configuration change
3. Hystrix execution

 

4. hello world

  

@ Log4jpublic class DemoHystrix extends HystrixCommand <Boolean> {private DemoService demoService; private Demo; protected DemoHystrix (DemoService demoService, demo Demo) {super (Setter. withGroupKey (HystrixCommandGroupKey. factory. asKey ("RemoteServiceX ")). andThreadPoolPropertiesDefaults (com. netflix. hystrix. hystrixThreadPoolProperties. setter (). withCoreSize (10 ). withMaximumSize (100)
// Refuse all services after the thread is saturated. withMaxQueueSize (-1)
// Make MaximumSize take effect. withAllowMaximumSizeToDivergeFromCoreSize (true )))
// The same thread used by fallback and execute. This configuration prevents fallback from preemptible execute threads. andThreadPoolKey (HystrixThreadPoolKey. factory. asKey ("RemoteServiceXFallback"); this. demoService = demoService; this. demo = demo ;}@ Override protected Boolean run () throws Exception {return demoService. queryDemoById (29 )! = Null;} @ Override protected Boolean getFallback (){
// You can handle System. out. println ("~~~~~~~~~~~~~~~~~ This is fallback "+ getExecutionException (). getMessage (); return false ;}}

This mode is generally out of the Framework (spring is not used). Hystrix is designed to run a command instance only once. If

DemoHystrix demoHystrix = new DemoHystrix(demoService,demo);        demoHystrix.execute();        demoHystrix.execute();

An exception will be thrown directly, so this explains why each Command must have a CommandKey so that the same command is executed in the same thread pool, you can even define the concept of a service group.

 

5. Use of hystrix in spring mvc

We can see from the above method that hystrix does not depend on any framework. It is just a set of command modes, and you can not even use it in service governance, it can be used in any scenario you need, but due to historical issues, if you want to use hystrix without modifying too much code, hystrix provides the hystrix-javanica package

Introduce hystrix dependency using maven: <dependency> <groupId> com. netflix. hystrix </groupId> <artifactId> hystrix-javanica </artifactId> <version> 1.5.12 </version> </dependency>

 

Indispensable spring configuration...

@Configuration@Import(com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect.class)@EnableAspectJAutoProxypublic class AppConfig extends WebMvcConfigurerAdapter {}

The configuration is very simple, because hystrix is ready, that is, an aop is implemented to cut all the methods that execute the @ HystrixCommand, and then package them

HystrixInvokable.

 

Then you can directly use hystrix.

@Component@Slf4jpublic class WrapService {    @Reference(version = "1.0.0")    private DemoService demoService;    @Reference(version = "1.0.0")    private OtherService otherService;    @Reference(version = "2.0.0")    private OtherService otherService2;    public boolean demoServiceInsert(Demo demo){        DemoHystrix demoHystrix = new DemoHystrix(demoService,demo);        return demoHystrix.execute();    }    @HystrixCommand(groupKey = "DemoCommand", fallbackMethod = "getDemoBack",            threadPoolProperties={@HystrixProperty(name = "coreSize",value = "10"),                    @HystrixProperty(name = "maximumSize",value = "100"),                    @HystrixProperty(name = "allowMaximumSizeToDivergeFromCoreSize",value = "true")})    public Demo getDemo(){        return demoService.queryDemoById(29);    }    private Demo getDemoBack(){        log.info("getDemoBack");        return new Demo();    }    public OtherService getOtherService(){        return otherService;    }    public OtherService getOtherService2(){        return otherService2;    }}

Like the service just now, in this case, exceptions cannot be obtained in fallback, and all other configurations can be completed in annotations.

 

6. Summary

Hystrix may lose some performance to a certain extent. According to the official documentation, if it is set well, it will probably reach 99.5% of the original, but this brings great control and flexibility to dependent services, it is easy to use and does not require much learning cost. What's more valuable is that it provides a feasible method for old systems to switch from Synchronous mode to asynchronous mode or reactive mode, this is amazing.

 

I forgot to talk about monitoring, but it is very simple. If you are interested in Hystrix, please refer to this article:

Http://tech.lede.com/2017/06/15/rd/server/hystrix/

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.