其他分享
首页 > 其他分享> > Hystrix(五)

Hystrix(五)

作者:互联网

HyStrix重要概念

  1. 服务降级

    • 服务器忙,请稍后再试,不让客户端等待并立刻返回一个友好提示,fallback
    • 哪些情况会发出降级
      *程序运行异常
      *超时
      *服务熔断触发服务降级
      *线程池/信号量也会导致服务降级
  2. 服务熔断

    • 类比保险丝达到最大服务访问后,直接拒绝访问,拉闸限电,然后调用服务降级的方法并返回友好提示
    • 就是保险丝 服务的降级->进而熔断->恢复调用链路
  3. 服务限流

    • 秒杀高并发等操作,严禁一窝蜂的过来拥挤,大家排队,一秒钟N个,有序进行

如何解决?解决的要求

  1. 超时导致服务器变慢(转圈) 超时不再等待

  2. 出错(宕机或程序运行出错) 出错要有兜底

  3. 解决

    • 对方服务(8001)超时了,调用者(80)不能一直卡死等待,必须有服务降级
    • 对方服务(8001)down机了,调用者(80)不能一直卡死等待,必须有服务降级
    • 对方服务(8001)ok,调用者(80)自己有故障或有自我要求(自己的等待时间小于服务提供者)

注:降级方法除了方法体内容与原方法不同,其它都要相同

一、降级

在服务端

  1. 导pom
<dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  1. 主启动类加@EnableCircuitBreaker注解
  2. 在service层写服务降级配置
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    //fallbackMethod:本方法出错、或者超时后执行的方法。
    //commandProperties :配置的集合
    //HystrixProperty:配置项
    //name :配置项的类型
    //value :值
    //在这里表示,如果该方法执行时间超过3秒,执行降级方法
    public String paymentInfo_TimeOut(Integer id){
        int timeNum=5;
        try {
            TimeUnit.SECONDS.sleep(timeNum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:"+Thread.currentThread().getName()+"paymentInfo_TimeOut,id:"+id+"\t"+"耗时:"+timeNum+"秒~~";
    }

    public String paymentInfo_TimeOutHandler(Integer id){
        return "我是8001,我出错啦!paymentInfo_TimeOut,id:"+id+"\t"+"┭┮﹏┭┮";
    }

客户端

  1. pom
<dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  1. 主启动类添加@EnableHystrix注解
  2. yml启用hystrix
#feign 日志以什么级别监控那个接口
feign:
  hystrix:
    enabled: true
  1. 在controller层写降级配置及方法
/*@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
           @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
   })*/
   // @HystrixCommand
   @GetMapping("/hystrix/timeOut/{id}")
   public String paymentInfo_timeOut(@PathVariable("id") Integer id){
       int i=10/0;
       return paymentHystrixService.paymentInfo_timeOut(id);
   }

   public String paymentInfo_TimeOutHandler(Integer id){
       return "我是消费者:运行出错啦!  "+"paymentInfo_TimeOutHandler,id:"+id+"\t"+"┭┮﹏┭┮";
   }
  1. *还可以写默认的降级方法,避免一个方法,一个降级方法,使得代码过度冗余*

    • 在该类上添加@DefaultProperties(defaultFallback = “payment_Global_FallbackMethod”)注解
    • 写降级方法
    • 在原方法上添加@HystrixCommand注解即可
  2. 还可以在service层做手脚,也就是写一个类实现被@FeignClient注解的接口,然后为每个方法写一个降级方法,最后在@FeignClient()里面加上@FeignClient(fallback=实现类名称.class即可)

二、熔断

概念
在这里插入图片描述
为了防止微服务都用了来处理该方法使得其他方法也变得卡顿。
在这里插入图片描述
可以设置触发条件,例如:
在10秒内,访问10次,出错率为60%,就会熔断(调用降级方法)。而他的高级之处在于,它会在一段时间后,试着访问该方法,如果还是出错,那么它又会继续等,而如果成功,则恢复正常。

配置服务端
在service里

/**
     * 服务的降级->进而熔断->恢复调用链路
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),//失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("******id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功,流水号:" + serialNumber;
    }

    public String paymentCircuitBreaker_fallback(Integer id) {
        return "id 不能负数,请稍后再试,o(╥﹏╥)o id:" + id;
    }

其它可用参数

@HystrixCommand(fallbackMethod = "xxx_method",
           groupKey = "strGroupCommand",
           commandKey = "strCommarld",
           threadPoolKey = "strThreadPool",
           commandProperties = {
                   //设置隔离策略,THREAD 表示线程她SEMAPHORE:信号他隔离
                   @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
                   //当隔离策略选择信号他隔离的时候,用来设置信号地的大小(最大并发数)
                   @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "10"),
                   //配置命令执行的超时时间
                   @HystrixProperty(name = "execution.isolation.thread.timeoutinMilliseconds", value = "10"),
                   //是否启用超时时间
                   @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                   //执行超时的时候是否中断
                   @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
                   //执行被取消的时候是否中断
                   @HystrixProperty(name = "execution.isolation.thread.interruptOnCancel", value = "true"),
                   //允许回调方法执行的最大并发数
                   @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "10"),
                   //服务降级是否启用,是否执行回调函数
                   @HystrixProperty(name = "fallback.enabled", value = "true"),
                   @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
                   //该属性用来设置在滚动时间窗中,断路器熔断的最小请求数。例如,默认该值为20的时候,
                   //如果滚动时间窗(默认10秒)内仅收到了19个请求,即使这19个请求都失败了, 断路器也不会打开。
                   @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
                   // 该属性用来设置在熔动时间窗中表示在滚动时间窗中,在请求数量超过
                   // circuitBreaker.requestVolumeThreshold 的情况下,如果错误请求数的百分比超过50,
                   //就把断路器设置为“打开”状态,否则就设置为“关闭”状态。
                   @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
                   // 该属性用来设置当断路器打开之后的休眠时间窗。休眠时间窗结束之后,
                   //会将断路器置为"半开”状态,尝试熔断的请求命令,如果低然失败就将断路器继续设置为"打开”状态,
                   //如果成功就设置为"关闭”状态。
                   @HystrixProperty(name = "circuitBreaker.sleepWindowinMilliseconds", value = "5009"),
                   //断路器强制打开
                   @HystrixProperty(name = "circuitBreaker.force0pen", value = "false"),
                   // 断路器强制关闭
                   @HystrixProperty(name = "circuitBreaker.forceClosed", value = "false"),
                   //滚动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
                   @HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds", value = "10000"),
                   //该属性用来设置滚动时间窗统计指标信息时划分”桶"的数量,断路器在收集指标信息的时候会根据设置的时间窗长度拆分成多个"相"来累计各度量值,每个”桶"记录了-段时间内的采集指标。
                   //比如10秒内拆分成10个”桶"收集这样,所以timeinMilliseconds 必须能被numBuckets 整除。否则会抛异常
                   @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
                   //该属性用来设置对命令执行的延迟是否使用百分位数来跟踪和计算。如果设置为false,那么所有的概要统计都将返回-1.
                   @HystrixProperty(name = "metrics .rollingPercentile.enabled", value = "false"),
                   //该属性用来设置百分位统计的滚动窗口的持续时间, 单位为毫秒。
                   @HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds", value = "60000"),
                   //该属性用来设置百分位统计演动窗口中使用“桶”的数量。
                   @HystrixProperty(name = "metrics.rollingPercentile.numBuckets", value = "60000"),
                   // 该属性用来设置在执行过程中每个 “桶”中保留的最大执行次数。如果在滚动时间窗内发生超过该设定值的执行次数,就从最初的位置开始重写。例如,将该值设置为100,燎动窗口为10秒, 若在10秒内一 一个“桶 ” 中发生7500次执行,
                   //那么该“桶”中只保留最后的100次执行的统计。另外,增加该值的大小将会增加内存量的消耗, 并增加排序百分位数所需的计算
                   @HystrixProperty(name = "metrics.rollingPercentile.bucketSize", value = "100"),
                   //该属性用来设置采集影响断路器状态的健康快照(请求的成功、错误百分比) 的间隔等待时间。
                   @HystrixProperty(name = "metrics.healthSnapshot.intervalinMilliseconds", value = "500"),
                   //是否开启请求缓存
                   @HystrixProperty(name = "requestCache.enabled", value = "true"),
                   // HystrixCommand的执行和时间是否打印日志到HystrixRequestLog中
                   @HystrixProperty(name = "requestLog.enabled", value = "true"),
           },
           threadPoolProperties = {
                   //该参数用来设置执行命令线程他的核心线程数,该值 也就是命令执行的最大并发量
                   @HystrixProperty(name = "coreSize", value = "10"),
                   //该参数用来设置线程她的最大队列大小。当设置为-1时,线程池将使用SynchronousQueue 实现的队列,
                   // 否则将使用LinkedBlocakingQueue实现队列
                   @HystrixProperty(name = "maxQueueSize", value = "-1"),
                   // 该参数用来为队列设置拒绝阀值。 通过该参数, 即使队列没有达到最大值也能拒绝请求。
                   //該参数主要是対linkedBlockingQueue 队列的朴充,因为linkedBlockingQueue
                   //队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
                   @HystrixProperty(name = "queueSizeRejectionThreshold", value = "5"),
           }

hystrixDashboard(可视化配置)

  1. 创建maven项目
  2. 导pom
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
  1. 主启动类
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardMain9001 {

    public static void main(String[] args) {
        SpringApplication.run(HystrixDashboardMain9001.class,args);
    }
}
  1. yml
    server:
    port: 9001
  2. 需要在被检测的服务端的主启动类添加如下方法
 /**
     * 此配置是为了服务监控而配置,与服务器容错本身无关,springcloud升级后的坑
     * ServletRegistrationBean因为springboot的默认路径不是/hystrix.stream
     * 只要在自己的项目里配置上下文的servlet就可以了
     */
    @Bean
    public ServletRegistrationBean getservlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean<HystrixMetricsStreamServlet> registrationBean = new ServletRegistrationBean<>(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
  1. 先启动注册中心server,再启动监控,再启动服务端。运行截图:
    注:要先访问服务端,界面才会显示数据,不然会一直是loading.......
    在这里插入图片描述

标签:10,降级,name,Hystrix,value,HystrixProperty,id
来源: https://blog.csdn.net/weixin_46029176/article/details/111321154