spring cloud——02(Hystrix服务降级、熔断)

hystrix(服务故障处理)

  • hystrix是什么:
    hystrix当服务发生故障时提供一些解决方案,防止一个服务出现故障引发雪崩导致整个系统瘫痪。hystrix提高了分布式系统的可用性和稳定性。
  • 什么是服务降级、服务熔断:
    参考:服务降级与服务熔断区别

服务降级:从实际业务角度来考虑,在并发高峰期(秒杀)为了保证核心功能服务(秒杀业务)的可用性,就需要对某些不重要的服务(帮助中心之类的业务)降级处理,也就是当服务器压力过大时不重要的业务直接不处理或者简单处理(直接返回友情提示)。可以理解为舍小保大。

简而言之:服务降级是从整个系统负荷情况来考虑,对某些不重要的业务进行服务降级处理,可以自动降级、也可以是管理员手动降级。

服务熔断:针对的是一条服务调用链A——>B——>C——>D。当C发生故障时。B调用C就会一直得不到结果而一直等待(这个过程是消耗服务器资源的)。B一直等待C返回的结果。然后A也一直等待B返回的结果。C的故障引起了B、A…的集体故障,就会引发雪崩效应,集体故障。而服务熔断就是要解决这个服务链调用引发的雪崩效应。

1、服务降级——服务端(服务提供者),一般写在客户端

  1. 导入pom依赖
<!--hystrix-->
<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
 </dependency>
  1. 配置yml
    yml不需要配置,netflix。根以前的服务服务提供者配置就好
server:
  port: 8001

spring:
  application:
    name: cloud-provider-hystrix-payment  #这个名称就是注册进eureka注册中心的服务名字(Application)

eureka:
  client:
    #表示是否将自己注册进Eurekaserver默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
#      defaultZone: http://localhost:7001/eureka,http://127.0.0.1:7002/eureka   #向那个注册中心进行注册
      defaultZone: http://localhost:7001/eureka #单击版
  instance:
    instance-id: PaymentHystrix8001 # 给EurekaUI界面的服务ip起一个别名
    prefer-ip-address: true #鼠标停留时是否在左下角显示ip
  1. 开启hystrix功能
/*
* springboot启动类*/
@SpringBootApplication
@EnableEurekaClient //开启eureka Client端,向注册中心注册自己,并提供服务
@EnableCircuitBreaker //开启服务降级(Hystrix)的功能
public class PaymentHygtrixMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentHygtrixMain8001.class,args);
    }
}
  1. 具体的服务降级解决方案

怎么触发服务降级:

  • 服务抛出异常
  • 服务请求超过指定时间
  • 服务器宕机
package com.lihua.springcloud.service.impl;


import com.lihua.springcloud.pojo.Payment;
import com.lihua.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 
 * 业务层,被控制层调用
 * @author 15594
 */
@Service
@Slf4j
public class PaymentServiceImpl implements PaymentService {
   /**
    *
    * 服务端:
    * 1、服务降级
    *fallbackMethod = "paymentInfo_TimeOutHandler"指定服务出错后的处理方法
    * commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")} 设置服务等待时间,超过后调用出错处理方法
    * */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler" ,
            commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")})
    @Override
    public String paymentInfo_TimeOut(Integer id) {

        //当代码报错的时候也会调用,降级的方法
        //比如:int i = 10/0;

        try {
            TimeUnit.MILLISECONDS.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:  "+Thread.currentThread().getName()+" id:  "+id+"\t"+"O(∩_∩)O哈哈~"+"  耗时(秒): 3";
    }
    //服务降级解决方案
    public String paymentInfo_TimeOutHandler(Integer id) {

        return "线程池:  "+Thread.currentThread().getName()+" id:  "+id+"\t"+"服务出错或者请求超时,请稍后再试 /(ㄒoㄒ)/~";
    }
}

注意:上面这种解决方案会有,1、代码膨胀(因为每个服务都要写一个服务降级方案)、2、代码耦合度高(业务逻辑代码与服务降级代码耦合了)的弊端

  • 解决代码膨胀:
    指定公共的(全局通用的)服务降级方案
    1、编写共解决降级方案,注意方法不能带参数
    2、在类上指定默认的降级方案:@DefaultProperties(defaultFallback = “payment_Global_FallbackMethod”)
    3、在需要使用公共解决方案的方法上添加注解:@HystrixCommand()不指定fallbackMethod 参数就默认使用全局
package com.lihua.springcloud.service.impl;


import com.lihua.springcloud.pojo.Payment;
import com.lihua.springcloud.service.PaymentService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 *
 * 业务层,被控制层调用
 * @author 15594
 */
@Service
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class PaymentServiceImpl implements PaymentService {

    /**
     * 使用全局服务降级解决方案,不指定fallbackMethod 参数就默认使用全局
     * @HystrixCommand表示使用全局(默认)方案
     **/
    @Override
    @HystrixCommand(commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")})
    public String PaymentInfo_OK(Integer id) {

        //当id为0时,会报运行时异常
        int i = 10/id;

        return "线程池"+Thread.currentThread().getName()+"PaymentInfo_OK"+id+"O(∩_∩)O哈哈~";
    }


    /**
    * 服务端:
    * 1、服务降级
    * fallbackMethod = "paymentInfo_TimeOutHandler"指定服务出错后的处理方法
    * commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")} 设置服务等待时间,超过后调用出错处理方法
    * */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler" ,
            commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")})
    @Override
    public String paymentInfo_TimeOut(Integer id) {

        //当代码报错的时候也会调用,降级的方法
        //比如:int i = 10/0;
        try {
            TimeUnit.MILLISECONDS.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:  "+Thread.currentThread().getName()+" id:  "+id+"\t"+"O(∩_∩)O哈哈~"+"  耗时(秒): 3";
    }
    //服务降级解决方案
    public String paymentInfo_TimeOutHandler(Integer id) {

        return "线程池:  "+Thread.currentThread().getName()+" id:  "+id+"\t"+"服务出错或者请求超时,请稍后再试 /(ㄒoㄒ)/~";
    }

    //全局服务降级方案,注意全局服务降级方法不能有参数
    public String payment_Global_FallbackMethod() {

        return "线程池:  "+Thread.currentThread().getName()+"\t"+"(全局)服务出错或者请求超时,请稍后再试 /(ㄒoㄒ)/~";
    }


}

注意:全局服务降级方法不能有参数

  • 代码耦合需要结合openfeign解决,因此在客户端中展示

2、服务降级——客户端

客户端需要配合openfeign使用

  1. 导入pom
 <!--openfeign-->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-openfeign</artifactId>
 </dependency>
 <!--hystrix-->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
 </dependency>

  1. 配置yml
  port: 81

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:7001/eureka

#开启
feign:
  hystrix:
    enabled: true

  1. 开启hystrix和openfeign
@SpringBootApplication
@EnableFeignClients  //使用并开启feign
@EnableHystrix //开启消费端 服务降级
public class OrderFeignHystrixMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignHystrixMain80.class,args);
    }
}
  1. 配置openfeign负载均衡接口,配了这个接口后会自动生成实现类
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT")  //负载均衡策略在yml中配置
@Component //没有注入spring可能会报错
public interface PaymentFeignService {

    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id);

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
  1. 在控制层实现服务降级
package com.lihua.springcliud.controller;

import com.lihua.springcliud.service.PaymentFeignService;

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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * 客户端服务降级
 * @author 15594
 */
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystirxController {

    @Autowired
    private PaymentFeignService paymentFeignService;


    /**
     * 使用默认的(全局降级方案)
     * */
    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    @HystrixCommand(commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")})
    public String paymentInfo_OK(@PathVariable("id") Integer id)
    {
        return paymentFeignService.paymentInfo_OK(id);
    }

    /**
     *
     * 客户端(消费端):
     * 1、服务降级
     *fallbackMethod = "paymentInfo_TimeOutHandler"指定服务出错后的处理方法
     * commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")} 设置服务等待时间,超过后调用出错处理方法
     * */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler" ,
            commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")})
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id)
    {

        //当代码报错的时候也会调用,降级的方法
        //比如:int i = 10/0;
        log.info(paymentFeignService.paymentInfo_TimeOut(id));

        return paymentFeignService.paymentInfo_TimeOut(id);
    }

    //服务降级解决方案
    public String paymentInfo_TimeOutHandler(@PathVariable("id") Integer id)
    {
        return "消费端:81 "+" id:  "+id+"\t"+"服务出错或者请求超时,请稍后再试 /(ㄒoㄒ)/~";
    }

    //全局服务降级方案,注意全局服务降级方法不能有参数
    public String payment_Global_FallbackMethod() {

        return "消费端:81"+"(全局)服务出错或者请求超时,请稍后再试 /(ㄒoㄒ)/~";
    }
}

上面的代码还没有解决代码耦合度高(业务逻辑代码与服务降级代码耦合了)这个弊端

  1. 解决代码耦合
  • 将所有的服务降级解决方法统一放到这个类中
/**
 *
 * 将服务降级解决方案抽取到这个类进行管理,解耦合
 * @author 15594
 */
@Component
public class PaymentFallbackServiceImpl implements PaymentFeignService {
    @Override
    public String paymentInfo_OK(Integer id) {
        return "------客户端服务降级:paymentInfo_OK——————————";
    }

    @Override
    public String paymentInfo_TimeOut(Integer id) {
        return "------客户端服务降级:paymentInfo_TimeOut——————————";
    }
}
  • 指定服务降级的类fallback = PaymentFallbackServiceImpl.class
    当服务出现故障时会找到指定的类,再按照方法名找到具体的降级方案。
package com.lihua.springcliud.service;



import com.lihua.springcliud.service.impl.PaymentFallbackServiceImpl;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackServiceImpl.class )  //负载均衡策略在yml中配置
@Component //没有注入spring可能会报错
public interface PaymentFeignService {

    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id);

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}

  • 简化控制层
package com.lihua.springcliud.controller;

import com.lihua.springcliud.service.PaymentFeignService;

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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * 客户端服务降级
 * @author 15594
 */
@RestController
@Slf4j
public class OrderHystirxController {

    @Autowired
    private PaymentFeignService paymentFeignService;


    public String paymentInfo_OK(@PathVariable("id") Integer id)
    {
        return paymentFeignService.paymentInfo_OK(id);
    }

   
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id)
    {

        //当代码报错的时候也会调用,降级的方法
        //比如:int i = 10/0;
        log.info(paymentFeignService.paymentInfo_TimeOut(id));

        return paymentFeignService.paymentInfo_TimeOut(id);
    }
}

这样就能实现服务降级了。

注意:当同时配置了 fallback = PaymentFallbackServiceImpl.class 和 @HystrixCommand()。优先以@HystrixCommand()为主。

3. 服务熔断——一般在服务端(生产者)实现

Hystrix的服务熔断机制:当服务链路的某个微服务多次出错时(响应时间太长),会启动服务熔断,自动进行服务降级。降级后每隔一段时间会试探一下链路故障是否恢复,当恢复后会关闭熔断,恢复调用链路
在Spring Cloud框架里,熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,
当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制。熔断机制的注解是@HystrixCommand。

  1. 导入pom
<!-- 没用新依赖需要导入,这里导入hutool工具报获取UUID-->
 <dependency>
    <groupId>cn.hutool</groupId>
     <artifactId>hutool-all</artifactId>
     <version>5.1.0</version>
 </dependency>
  1. 配置yml

yml需要改动

server:
  port: 8001

spring:
  application:
    name: cloud-provider-hystrix-payment  #这个名称就是注册进eureka注册中心的服务名字(Application)

eureka:
  client:
    #表示是否将自己注册进Eurekaserver默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
#      defaultZone: http://localhost:7001/eureka,http://127.0.0.1:7002/eureka   #向那个注册中心进行注册
      defaultZone: http://localhost:7001/eureka #单击版
  instance:
    instance-id: PaymentHystrix8001 # 给EurekaUI界面的服务ip起一个别名
    prefer-ip-address: true #鼠标停留时是否在左下角显示ip
  1. 启动类无需改动
@SpringBootApplication
@EnableEurekaClient //开启eureka Client端,向注册中心注册自己,并提供服务
@EnableCircuitBreaker //开启服务降级(Hystrix)的功能
public class PaymentHygtrixMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentHygtrixMain8001.class,args);
    }
}
  1. 配置服务熔断
//===================服务熔断
    @HystrixCommand(
            fallbackMethod = "payment_CircuitBreaker_fallback",//降级方法
            commandProperties = {
                    //熔断策略:在时间窗口期10秒内,10次请求中有10*60%=6次请求错误(超时)就打开断路器
                    @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
                    @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000") //请求超时时间
            }
    )
    @Override
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if (id<0){
            throw new RuntimeException("******id 不能为负数");
        }
        //hutool工具生成UUID
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功"+serialNumber;

    }

    //全局服务降级方案,注意全局服务降级方法不能有参数
    public String payment_CircuitBreaker_fallback(@PathVariable("id") Integer id) {

        return "id 不能为负数,请再次尝试"+id;
    }
  1. 服务熔断结束
    服务熔断的过程:当请求失败(请求失败或者超时会调用服务降级方法)的次数达到阈值时,会触发服务熔断,打开断路器。打开断路器后即使请求是正常的也会短时间使用降级方案,断路器关闭的条件是,当请求成功的次数达到阈值时会自动关闭断路器。

  2. 全部配置

@HystrixCommand(fallbackMethod = "fallbackMethod", 
                groupKey = "strGroupCommand", 
                commandKey = "strCommand", 
                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 = "5000"),
                    // 断路器强制打开
                    @HystrixProperty(name = "circuitBreaker.forceOpen", 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秒内一个 “桶 ”中发生了500次执行,
                    // 那么该 “桶” 中只保留 最后的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 实现的队列,否则将使用 LinkedBlockingQueue 实现的队列。
                    @HystrixProperty(name = "maxQueueSize", value = "-1"),
                    // 该参数用来为队列设置拒绝阈值。 通过该参数, 即使队列没有达到最大值也能拒绝请求。
                    // 该参数主要是对 LinkedBlockingQueue 队列的补充,因为 LinkedBlockingQueue 队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
                    @HystrixProperty(name = "queueSizeRejectionThreshold", value = "5"),
                }
               )
public String doSomething() {
	...
}

4、服务监控

  1. 导入pom
 <!-- hystrix图像化页面监控-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>
<!--        被监控的服务必须导入这个依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
  1. 配置yml
server:
  port: 9001

  1. 启动类开启该功能
/**
 * Hygtrix图形化页面监控
 *
 * @author 15594
 */
@SpringBootApplication
@EnableHystrixDashboard //开启图形化页面监控
public class DashboardMian {
    public static void main(String[] args) {
        SpringApplication.run(DashboardMian.class,args);
    }
}
  1. 测试
    浏览器打开: http://localhost:9001/hystrix
    在这里插入图片描述
  2. 配置被监控者
    注意:被监控的服务必须导入这个依赖
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
package com.lihua.springcloud;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;

/*
* springboot启动类*/
@SpringBootApplication
@EnableEurekaClient //开启eureka Client端,向注册中心注册自己,并提供服务
@EnableCircuitBreaker //开启服务降级(Hystrix)的功能
public class PaymentHygtrixMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentHygtrixMain8001.class,args);
    }
    /**
     *此配置是为了服务监控而配置,与服务容错本身无关,springcloud升级后的坑
     *ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream",
     *只要在自己的项目里配置上下面的servlet就可以了
     *否则,Unable to connect to Command Metric Stream 404
     */
    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }

}

  1. 测试
    在这里插入图片描述
    第一次运行可以是空的

在这里插入图片描述
然后我们去请求这个微服务提供的url,比如:
http://localhost:8001/payment/hystrix/circuitBreaker/-1
http://localhost:8001/payment/hystrix/circuitBreaker/1
请求后监控页面就会出现数据

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值