Spring Cloud Learning (4)-Hystrix service fuse processing

Source: Internet
Author: User

Hystrix is an open source project dedicated to service fusing, when a dependent service party fails to become available, Hystrix has a so-called circuit breaker that, when turned on, intercepts the call to the faulty service directly, preventing further failures (similar to tripping in circuits, protecting home appliances).

Use steps: (still modified in the previous sample code)

First, add Hystrix dependency

Compile ' Org.springframework.cloud:spring-cloud-starter-hystrix '

Ii. Add annotations to the method that requires fusing

Package Com.cnblogs.yjmyzz.spring.cloud.study.service.controller;import Com.cnblogs.yjmyzz.spring.cloud.study.dto.userdto;import Com.cnblogs.yjmyzz.spring.cloud.study.service.client.userfeignclient;import Com.netflix.hystrix.contrib.javanica.annotation.hystrixcommand;import Com.netflix.hystrix.contrib.javanica.annotation.hystrixproperty;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.web.bind.annotation.getmapping;import org.springframework.web.bind.annotation.PathVariable; Import Org.springframework.web.bind.annotation.restcontroller;import java.util.Random; @RestControllerpublic class    Ordercontroller {@Autowired private userfeignclient userfeignclient;    Private final random rnd = new Random (System.currenttimemillis ());            @GetMapping ("/order/{userid}/{orderno}") @HystrixCommand (Fallbackmethod = "Findorderfallback", commandproperties = { @HystrixProperty (name = "Execution.isolation.thread.timeoutInMilliseconds", value = "10")}) public String findorder (@PathVariable Integer userId, @PathVariable String OrderNo) throws Interruptedexcept        Ion {Thread.Sleep (Rnd.nextint (2000));        Userdto user = Userfeignclient.finduser (userId); if (user! = null) {return user.getusername () + "order" + OrderNo + "Found!        "; } return "user does not exist!    "; The public String findorderfallback (Integer userId, String orderno) {return ' Order lookup failed!    ";   }}

Note the Hystrixcommand annotation added on FindOrder, which means that if the method call fails, it switches to the alternate method Findorderfallback, and also sets a time-out of 1000ms, which is 1 seconds. In other words, if the FindOrder method does not return a result within 1s, the call fails, and it switches to the alternate method Findorderfallback.

Note: In order to facilitate the demonstration, deliberately on the findorder for a period of 2 seconds, so expected this method, should be occasionally timed out, occasionally normal.

For more properties on Hystrixproperty, refer to the official documentation on GitHub: https://github.com/Netflix/Hystrix/wiki/Configuration

third,the main entrance to enable Hytrix fuse

@EnableDiscoveryClient @springbootapplication@enablefeignclients@enablecircuitbreakerpublic class Serviceconsumer {public    static void Main (string[] args) {        springapplication.run (serviceconsumer.class, args);}    }

When enabled, accessing http://localhost:8002/order/1/100, you can see output similar to the following:

Normally, a similar output is returned, which, if timed out, will return:

In addition, Spring-boot's acturator also provides the health endpoint to view the Hystrix status, viewing the Http://localhost:8002/health

This indicates that the Hystrix circuit breaker is not open, if http://localhost:8002/order/1/100 this page mad brush (default to 5 seconds to fail more than 20 times), or simply to stop the service-provider, this state will become:

Indicates that the circuit breaker is open at this time.

Iv.hystrix Monitoring

The health endpoint can only see the overall state of the circuit breaker, but the details are not detailed enough to expose an endpoint by default as long as the Hystrix feature is enabled Hystrix.stream

Access http://localhost:8002/Hystrix.stream to view detailed data

Note: This page will continue to output new content in real time (if any), the first visit, if you see all the way, but there is no content, indicating that the service corresponding to the method of no one call, you can access the FindOrder method, then look at this page.

Obviously, a bunch of dense text, no one would like to see, Spring-cloud long thought of this, provides a hystrix-dashboard function, you can use a graphical interface to interpret the data.

One more project, named Hystrix-dashboard,build.gradle reference below:

Buildscript {    repositories {        maven {            url "http://maven.aliyun.com/nexus/content/groups/public/"        }    }    dependencies {        classpath ("Org.springframework.boot:spring-boot-gradle-plugin:1.5.4.release")    }}apply Plugin: ' Org.springframework.boot ' dependencymanagement {    Imports {        Mavenbom ' Org.springframework.cloud: Spring-cloud-dependencies:dalston. RELEASE "    }}dependencies {    compile ' org.springframework.cloud:spring-cloud-starter-eureka '    compile ' Org.springframework.cloud:spring-cloud-starter-hystrix-dashboard '    compile ' org.springframework.boot: Spring-boot-starter-actuator '}

The main function is as follows:

Package Com.cnblogs.yjmyzz.spring.cloud.study.hystrix;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.cloud.client.discovery.enablediscoveryclient;import org.springframework.cloud.netflix.hystrix.dashboard.enablehystrixdashboard;/** * Created by yangjunming on 2017/6/ */@SpringBootApplication @enablehystrixdashboard@enablediscoveryclientpublic class Hystrixdashboardapplication {public    static void Main (string[] args) {        springapplication.run (hystrixdashboardapplication.class, args);}    }

Of course, this is also a micro-service, you can also register to Eureka, refer to the following configuration:

Spring:  application:    name:hystrix-dashboardserver:  Port:8035eureka:  instance:    Prefer-ip-address:true  Client:    service-url:      defaultzone:http://yjmyzz:[email Protected]:8100/eureka , Http://yjmyzz:[email Protected]:8200/eureka,http://yjmyzz:[email Protected]:8300/eureka

After the success is enabled, accessing Http://localhost:8035/hystrix will appear similar to the following interface:

In the 1th input box, fill in the Hystrix.steam address you want to monitor, then name it here and then click Monitor Steam to see the chart:

This is obviously a lot more friendly than plain text. There is also a problem, if there are multiple Hystrix.stream address monitoring at the same time, or the data of multiple addresses together, how to do? There is a turbine on GitHub that is specifically designed to solve this problem, and you can study it on your own.

Finally, enclose the example code in the article address: Https://github.com/yjmyzz/spring-cloud-demo

Spring Cloud Learning (4)-Hystrix service fuse processing

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.