一.开启熔断器
1、引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、 主程序打上@EnableHystrix标签,开启熔断器功能
@SpringBootApplication
@EnableEurekaClient
/**
* @EnableHystrix: 开启 hystrix ,开启熔断器功能
*/
@EnableHystrix
@EnableHystrixDashboard //开启 Hystrix Dashboard (断路器:Hystrix 仪表盘)
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
//如果赋予了restTemplate负载均衡的能力 就只能通过服务名去调了
@Bean
@LoadBalanced //赋予负载均衡的能力,默认是轮询
RestTemplate restTemplate(){
return new RestTemplate();
}
}
3、在ConsumerController中的方法上打上注解 @HystrixCommand注解,开启熔断器功能
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
//HystrixCommand:给方法启用熔断器功能,当出现访问故障,自动调用 fallbackMethod 指向的方法
@HystrixCommand(fallbackMethod = "fallback") //此方法开启熔断器
@RequestMapping("/consumer")
public String consumerTest(@RequestParam(value = "name") String name){
String forObject = restTemplate.getForObject("http://PROVIDER/provider?name=" + name, String.class);
return forObject;
}
public String fallback(String name){
return "出错啦!";
}
}
@HystrixCommand(fallbackMethod="fallback")
:声明一个失败回滚处理函数fallback,当queryUserById执行超时(默认是1000毫秒),就会执行fallback函数,返回错误提示。
4、测试:一次启动 EurekaServer,Provider,Consumer服务,访问地址 http://localhost:8083/consumer?name=andy ,你将会看到“andy你好呀这里是Producer服务”,
当关掉 Producer服务,再访问会出现:出错啦!
当Producer服务关掉,那么Consumer服务不能调用Producer服务的接口,那么马上回执行errorMethod方法进行故障处理。
5、这里需要注意, Hystix的超时时间默认也是1000ms,我们在配置的时候, Ribbon的超时时间一定要小于Hystix的超时时间。
我们可以通过 hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
来设置Hystrix超时时间。
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMillisecond: 10000 # 熔断超时时长:10000ms