一,引入必要的包
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>${hystrix.version}</version>
</dependency>
二、添加部分配置
调用方Application入口,增加@EnableHystrix
@SpringBootApplication
@EnableDiscoveryClient //开启eureka客户端发现功能
@EnableHystrix //开始hystrix
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
@LoadBalanced//开启Ribbon的负载均衡,调用时,可以通过user-service名字,找到对应的服务。
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
对应的方法,配置熔断时执行方法
@GetMapping("/{id}")
@HystrixCommand(defaultFallback = "defalutFallback")
public String queryById(@PathVariable Long id){
if(id == 1){
throw new RuntimeException("太忙了");
}
//String url = "http://localhost:9091/user/1";
// List<ServiceInstance> userInstances = discoveryClient.getInstances("user-service");
//
// ServiceInstance userInstance = userInstances.get(0);
//
// String url = "http://"+userInstance.getHost()+":"+userInstance.getPort()+"/user/"+id;
String url = "http://user-service/user/"+id;
log.info(url);
String forObject = restTemplate.getForObject(url, String.class);
log.info(forObject);
return forObject;
}
public String defalutFallback(){
return "默认提示:对不起,网络太拥挤了!";
}
四、熔断演示
先访问 http://localhost:8080/consumer/2
出现
再连续访问 http://localhost:8080/consumer/1
出现
再访问 http://localhost:8080/consumer/2
出现
五、部分hystrix配置
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 20000 # 在调用方配置,被该调用方的所有方法的超时时间都是该值,优先级低于下边的指定配置
circuitBreaker:
errorThresholdPercentage: 50 # 触发熔断错误比例阀值,默认50%
sleepWindowInMilliseconds: 10000 #熔断后休眠状态时长,默认值5秒
requestVolumeThreshold: 10 # 熔断触发最小请求次数,默认值为0