Springboot-微服务-微服务组件之服务管理-服务熔断雪崩-Hystrix-服务熔断

Hystrix-服务熔断

1.1 熔断原理

Hystrix-熔断状态模型

状态类型有三种:

  • Closed: 关闭状态(断路器关闭),所有请求正常访问

  • Opne: 开启状态(断路器打开),所有请求会被降级处理,Hystrix 会对请求情况计数,当一定时间内请求的百分比到达阈值,测出发熔断,断路器完全打开。默认的失败比阈值50%,请求次数不低于20次。

  • half Open : 半开状态,colsed 状态不用永久的,关闭后会进入休眠状态(默认时5s).之后断路器会自动进入半开状态。此时会释放部分请求通过,如果这些请求是健康的,则会完全关闭断路器,否则继续保持打开,再一次进入休眠。

配置要点


package com.caicai.Consumer.Control;


import com.caicai.Consumer.po.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
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.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "default_Fallback")//为所有方法添加降级处理逻辑
public class ConsumerControl {
    @Autowired
    private RestTemplate restTemplate;
//配置熔断策略
        @HystrixCommand(commandProperties = {

                @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),//设置超时统计次数
                @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//设置休眠时间窗
                @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60")//设置失败百分比
    }) //配置单个超时,时长
    public String queryById(@PathVariable("id") Long id)
    {

        String url = "http://user-service/user/"+id;
        String user = restTemplate.getForObject(url,String.class);
        return user;

    }
    //一对一的处理逻辑方法
    public String  queryById_Fallback( Long id)
    {
        return "系统繁忙!,请稍后再试!";

    }
    //通用的降级处理逻辑方法
    public String  default_Fallback()
    {
        return "系统繁忙!,请稍后再试!";

    }



}

注释

  • circuitBreaker.requestVolumeThreshold : 触发熔断的最小次数

  • circuitBreaker.sleepWindowInMilliseconds : 触发熔断的失败请求,最小占比,默认是50%

  • circuitBreaker.errorThresholdPercentage : 休眠时长,默认是5s

一般情况,熔断的超时,时长我们是不需要配置的,线程的超时,时长,一般来说,我们需要做人工干预的,有的服务就需要很长时间。

posted @ 2021-07-18 13:27  菜菜920  阅读(173)  评论(0编辑  收藏  举报