spring cloud之hystrix
1,hystrix降级(启动类上开启(@EnableHystrix)
01-1在接口上添加注解
@HystrixCommand(fallbackMethod ="payment_fail_handle",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
})
01-2 编写payment_fail_handle方法
缺点:每个方法上都要加,代码冗余
改进
02-1 在类上添加@DefaultProperties(defaultFallback = "payment_default_fallBackMethod")
在接口上添加@HystrixCommand
02-2 编写payment_default_fallBackMethod方法
在升级
03-1在调用service上加上@FeignClient(value = "CLOUD-PAYMENT-HYSTRIX-SERVECE",fallback = PaymentHystrixFallBackService.class)
03-2 编写PaymentHystrixFallBackService类实现service
2,hystrix熔断
在启动类上添加 @EnableCircuitBreaker
在需要熔断的方法上添加
@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"),//失败率达到多少后跳闸
})
解释:在10000(10秒)内,10次请求失败率达到60%,即该接口熔断,返回paymentCircuitBreaker_fallBack方法返回结果
编写 paymentCircuitBreaker_fallBack方法,该方法为熔断调用的方法
3,hystrix 限流
4,hystrix图形化dashboard搭建
新建moudle1模块(端口9001)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
在启动类上加@EnableHystrixDashboard
监测的模块
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
在启动类上添加@EnableCircuitBreaker
在启动类里注入
@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;
}
访问moudle1模块 http://localhost:9001/hystrix