Ribbon+Hystrix circuit breaker realizes the degradation and fusing of microservices

When the microservice is down, Ribbon cannot forward the request, so Hystrix is ​​introduced.

The core functions of Hystrix short circuiter:

  1. Degradation: When the background microservice is unavailable or the access timeout, it will turn to the execution of the degraded code, or return an error message, or return the cached data;
  2. Fuse: In the default configuration, the background microservice receives 20 requests within 10 seconds, and half of the requests (50%) have a request failure and degradation, then Hystrix opens the circuit breaker (the circuit breaker is closed by default), which means The background microservice is unavailable, let all requests execute the degraded code; when the circuit breaker is opened for 5 seconds, it turns into a half-opened state, which means that when a request arrives, it will try to forward it to the background microservice. If the request is successful, the short-circuiter is closed, which means that all requests can request to reach the background microservice; if the request still fails, the short-circuiter remains open.

1. Create a SpringBoot project and add dependencies:

Ribbon+Hystrix circuit breaker realizes the degradation and fusing of microservices

 

2. Add Hystrix dependency:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

3. Add the common tool class dependency of your own project:

Ribbon+Hystrix circuit breaker realizes the degradation and fusing of microservices

 

4. Make relevant configuration in application.yml file:

Ribbon+Hystrix circuit breaker realizes the degradation and fusing of microservices

 

5. Add annotations @EnableCircuitBreaker and @EnableDiscoveryClient to the main startup class:

These three annotations can be replaced by @SpringCloudApplication

Ribbon+Hystrix circuit breaker realizes the degradation and fusing of microservices

 

6. Create the RibbonController class, write the controller method of springMVC in this class, specify the corresponding downgrade method, and mark the specified downgrade method by annotation on the controller method:

package com.tedu.sp7.controller;
import java.util.List;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.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import com.tedu.sp01.pojo.Item;import com.tedu.sp01.pojo.Order;import com.tedu.sp01.pojo.User;import com.tedu.web.util.JsonResult;@RestControllerpublic class RibbonController {    @Autowired    private RestTemplate rt;    @GetMapping("/item-service/{orderId}")
    @HystrixCommand(fallbackMethod = "getItemsFB") //指定降级方法的方法名
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) {        return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);
    }    @PostMapping("/item-service/decreaseNumber")
    @HystrixCommand(fallbackMethod = "decreaseNumberFB")
    public JsonResult decreaseNumber(@RequestBody List<Item> items) {        return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
    }    /    @GetMapping("/user-service/{userId}")
    @HystrixCommand(fallbackMethod = "getUserFB")
    public JsonResult<User> getUser(@PathVariable Integer userId) {        return rt.getForObject("http://user-service/{1}", JsonResult.class, userId);
    }    @GetMapping("/user-service/{userId}/score") 
    @HystrixCommand(fallbackMethod = "addScoreFB")
    public JsonResult addScore(@PathVariable Integer userId, Integer score) {        return rt.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class, userId, score);
    }    /    @GetMapping("/order-service/{orderId}")
    @HystrixCommand(fallbackMethod = "getOrderFB")
    public JsonResult<Order> getOrder(@PathVariable String orderId) {        return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId);
    }    @GetMapping("/order-service")
    @HystrixCommand(fallbackMethod = "addOrderFB")
    public JsonResult addOrder() {        return rt.getForObject("http://order-service/", JsonResult.class);
    }    /    //降级方法的参数和返回值,需要和原始方法一致,方法名任意
    public JsonResult<List<Item>> getItemsFB(String orderId) {        return JsonResult.err("获取订单商品列表失败");
    }    public JsonResult decreaseNumberFB(List<Item> items) {        return JsonResult.err("更新商品库存失败");
    }    public JsonResult<User> getUserFB(Integer userId) {        return JsonResult.err("获取用户信息失败");
    }    public JsonResult addScoreFB(Integer userId, Integer score) {        return JsonResult.err("增加用户积分失败");
    }    public JsonResult<Order> getOrderFB(String orderId) {        return JsonResult.err("获取订单失败");
    }    public JsonResult addOrderFB() {        return JsonResult.err("添加订单失败");
    }}

Hystrix common configuration:

  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
    request timeout time, after timeout triggers failure downgrade
  • hystrix.command.default.circuitBreaker.requestVolumeThreshold The
    number of requests within 10 seconds, the default is 20. If the number is not reached, even if all requests fail, the circuit breaker will not be triggered to open
  • hystrix.command.default.circuitBreaker.errorThresholdPercentage The
    percentage of failed requests. When this percentage is reached, the circuit breaker is triggered to open
  • hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds After the
    circuit breaker is opened, how long is it allowed to try to access again (half-open), if it fails, the circuit breaker will remain open. If the access is successful, the circuit breaker will be closed. The default is 5000

Guess you like

Origin blog.csdn.net/qq_45401061/article/details/108721325