Springcloud Starter Breaker Hystrix (iv)

Source: Internet
Author: User

What is a circuit breaker?

The circuit breaker model originates from Martin Fowler's circuit breaker. "Circuit Breaker" itself is a switch device, used in the circuit to protect the line overload, when the circuit has a short circuit, "circuit breaker" can timely cut off the fault circuit, to prevent the occurrence of overload, heat, and even fire serious consequences.

In a distributed architecture, the role of the circuit breaker pattern is similar, when a service unit fails (similar to a short-circuit with electrical appliances), through the fault monitoring of the circuit breaker (similar to a fuse fuse), to the caller returned an error response, rather than a long wait. This does not cause the thread to fail to be released for a long time because of the invocation of the fault service, thus avoiding the spread of the fault in the distributed system.

Netflix Hystrix
The hystrix is used in spring cloud to realize the function of the circuit breaker. Hystrix is one of Netflix's open source MicroServices framework packages designed to provide greater fault tolerance for latency and failures by controlling the nodes that access remote systems, services, and third-party libraries. The Hystrix features thread and signal isolation with fallback mechanism and breaker functionality, request caching and request packaging, and monitoring and configuration.

Let's take a simple example to introduce the use of spring cloud Hystrix

First add the spring cloud Hystrix dependencies to the project:

<dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-hystrix</artifactId></dependency>在工程的启动类中加入@EnableCircuitBreaker开启熔断器功能@SpringBootApplication@EnableDiscoveryClient@EnableCircuitBreakerpublic class Application {    @Bean    @LoadBalanced    public RestTemplate restTemplate(){        return new RestTemplate();    }    public static void main(String[] args){        SpringApplication.run(Application.class,args);    }}

You can also use the springcloud corresponding @springcloudapplication annotation to decorate the startup class, as you can see from the code, which contains the other three annotations, as well as a standard Springcloud program that contains service discovery and fusing mechanisms. You are welcome to study the relevant technology to understand the source of friends directly seeking exchange and sharing technology: 2147775633

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootApplication@EnableDiscoveryClient@EnableCircuitBreakerpublic @interface SpringCloudApplication {}

Added Computeservice class to specify callback methods by adding @hystrixcommand annotations on functions using the Ribbon consumption service

@Servicepublic class ComputeService {    @Autowired    private RestTemplate restTemplate;    @HystrixCommand(fallbackMethod = "addServiceFallback")    public String addService(){        return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();    }    public String addServiceFallback() {        return "error";    }}

The controller that provides the rest interface changes to call Computeservice's AddService

@RestControllerpublic class ConsumerController {    @Autowired    private ComputeService computeService;    @RequestMapping(value = "/add", method = RequestMethod.GET)    public String add() {        return computeService.addService();    }}

Verify the callback for the circuit breaker

Start Eureka-server, Compute-service, Eureka-ribbon project in turn
Access http://localhost:1111/to see the status of the registry
Visit Http://localhost:3333/add, page display: 30
After you close the Compute-service service and then visit Http://localhost:3333/add, the page displays: Error
Feign using Hystrix

Note that this is said to be "use", there is no mistake, we do not need to introduce hystix,feign in the Feigh project has relied on hystrix, we can do before any modification, try the following your operation:

Start Eureka-server, Compute-service, Eureka-feign project in turn
Access http://localhost:1111/to see the status of the registry
Access Http://localhost:3333/add, call Eureka-feign's service, the service will go to invoke Compute-service service, calculate the value of 10+20, page display 30
Close the Compute-service service, Access Http://localhost:3333/add, we get the following error message

Whitelabel Error Page

This application have no explicit mapping for/error, so is seeing this as a fallback.

Sat June 22:10:05 CST 2016
There is an unexpected error (type=internal Server error, status=500).
Add Timed-out and no fallback available.
If you are careful enough, you will find that the error in the Ribbon is different, see Add timed-out and no fallback available this sentence, perhaps you have guessed what, look at our console, You can see that the error message comes from Hystrix-core-1.5.2.jar, so in this project, we are going to learn how to use the integrated Hystrix in the feign.

Use the Fallback property in the @feignclient annotation to specify the callback class

@FeignClient(value = "compute-service", fallback = ComputeClientHystrix.class)public interface ComputeClient {    @RequestMapping(method = RequestMethod.GET, value = "/add")    Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);}

Create the callback class Computeclienthystrix, implement the @feignclient interface, at this time to implement the method is corresponding to the @feignclient interface mapping fallback function.

@Componentpublic class ComputeClientHystrix implements ComputeClient {    @Override    public Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b) {        return -9999;    }}

Then verify with the previous method that the page returns 9999 if the Compute-service service is unavailable.

Springcloud Starter Breaker Hystrix (iv)

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.