在 Ribbon中使用断路器
添加依赖
在项目pom
加上hystrix
的依赖
<!-- hystrix 断路器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
服务注册
在程序的启动类RibbonConsumerApplication
通过 @EnableHystrix
开启Hystrix
断路器监控
@EnableHystrix
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class, args);
}
}
消费提供者方法
修改 ConsumerController
类的,hello
方法,加上注解@HystrixCommand(fallbackMethod = "defaultStores")
该注解对该方法创建了熔断器的功能 ,并指定了defaultStores
熔断方法,熔断方法直接返回了一个字符串, "feign + hystrix ,提供者服务挂了"
@HystrixCommand
表明该方法为hystrix包裹,可以对依赖服务进行隔离、降级、快速失败、快速重试等等hystrix
相关功能 该注解属性较多,下面讲解其中几个
- fallbackMethod 降级方法
- commandProperties 普通配置属性,可以配置HystrixCommand对应属性,例如采用线程池还是信号量隔离、熔断器熔断规则等等
- ignoreExceptions 忽略的异常,默认HystrixBadRequestException不计入失败
- groupKey() 组名称,默认使用类名称
- commandKey 命令名称,默认使用方法名
/**
* 描述:调用提供者的 `home` 方法
*
**/
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "defaultStores")
@GetMapping(value = "/hello")
public String hello() {
return restTemplate.getForEntity("http://eureka-provider/", String.class).getBody();
}
public String defaultStores() {
return "Ribbon + hystrix ,提供者服务挂了";
}
}
测试断路器
依次启动项目:
spring-cloud-eureka-service
spring-cloud-eureka-provider-1
spring-cloud-eureka-provider-2
spring-cloud-eureka-provider-3
spring-cloud-ribbon-consumer-hystrix
启动该工程后,访问服务注册中心,查看服务是否都已注册成功:http://localhost:8761/
在命令窗口curl http://localhost:9000/hello
,发现一切正常
或者浏览器get 请求http://localhost:9000/hello
F5 刷新
停止 spring-cloud-eureka-provider-1
提供者,端口为:8081服务
再次访问命令窗口curl http://localhost:9000/hello
,断路器已经生效,提示:Ribbon + hystrix ,提供者服务挂了。