一、hystrix
hystrix主要实现熔断和隔离,限流的功能基本没有,通过fallback实现服务降级和快速失败。核心是HystrixCommand。配置主要包含exection、fallback、circuitBreaker、metric、threadPool等。
二、加入依赖包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
</dependency>
三、在application.yml中加入配置
feign:
hystrix:
enabled: true
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
strategy: THREAD
thread:
timeoutInMilliseconds: 8000
interruptOnTimeout: true
interruptOnCancel: true
fallback:
enabled: true
isolation:
semaphore:
maxConcurrentRequests: 2
四、在访问接口上实现熔断、隔离和服务降级
@HystrixCommand(commandKey = "circuitBreakerCommand",threadPoolKey = "circuitBreakerPool",fallbackMethod = "circuitBreakerFallbackMethod",
commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"),
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000")
},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "5")
})
@GetMapping("/circuitBreakerHello/{id}")
public String circuitBreakerHello(@PathVariable("id") int id) {
if(id==2){
throw new RuntimeException("exception");
}
return "sucessful execution" ;
}
public String circuitBreakerFallbackMethod(int id) {
return "param "+id+" is wrong. circuitBreaker has been valid";
}
五、启动类上添加@EnableHystrix
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
@MapperScan("com.sboot.dao")
public class ConsulConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsulConsumerApplication.class, args);
}
}
六、测试
1、在浏览器中多次刷新如下地址,导致熔断打开
2、当访问正常得路径http://localhost:8082/circuitBreakerHello/1,也走服务降级:
3、过一会,过了休眠期,再访问正常路径,可以正常访问