Netflix的创造了一个调用的库 Hystrix 实现了断路器。在微服务架构中,通常有多层服务调用。
底层服务出现故障可能导致用户级联故障。当调用特定服务达到一定阈值时(Hystrix中的默认值为5秒内的20次故障),电路打开,不进行通话。在开路的情况下,可以使用备用的方法进行处理。如下图:
当服务B挂掉或者访问超时后,调用Fallback
1、pom依赖:
<dependency>
<!-- hystrix 断路器 -->
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
注意:一定要加上commons-lang3的依赖,不然在访问的时候,会报找不到 org.apache.commons.lang3.Validate 类的异常
2、入口加上@EnableCircuitBreaker注解,启动断路器
@SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker //开启断路器 public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } }
3、使用RestTemplate调用远程服务
@RestController public class IndexController { @Autowired private RestTemplate restTemplate; @GetMapping("/find/{id}") public UserEntity findById(@PathVariable Long id) { return restTemplate.getForObject("http://service-provider/find/" + id, UserEntity.class); } /** * 测试hystrix * * 1、调用远程服务超时后,断路器打开,调用getOneFallBack (如果远程服务挂了,会立马调用getOneFallBack,超时时间不起作用) * 2、超时时间为2000毫秒(默认1秒) */ @GetMapping("/getOne/{id}") @HystrixCommand(fallbackMethod = "getOneFallBack", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000") }) public UserEntity getOne(@PathVariable Long id) { UserEntity user = restTemplate.getForObject("http://service-provider/find/" + id, UserEntity.class); return user; } /** * 参数跟返回类型必须跟上面的一样,不然会报找不到该方法的错 */ public UserEntity getOneFallBack(Long id) { UserEntity user = new UserEntity(); user.setId("1000"); user.setAge(12); return user; } }
@HystrixCommand
由名为“javanica”的Netflix contrib库提供 。Spring Cloud在连接到Hystrix断路器的代理中使用该注释自动包装Spring bean。断路器计算何时打开和关闭电路,以及在发生故障时应该做什么。该注解属性较多,下面讲解常用的几个:
1、fallbackMethod 降级方法
2、commandProperties 普通配置属性,可以配置HystrixCommand对应属性,例如采用线程池还是信号量隔离、熔断器熔断规则等等
对于hystrix的配置,也可以在yml文件中配置。如:
hystrix: command: default: execution: timeout: enabled: true #是否开启超时(默认开启) isolation: thread: timeoutInMilliseconds: 5000 #超时时间(默认1000毫秒)
测试结果:
1、service-provider正常时,返回结果正常
2、service-provider挂掉时,立马调用降级方法 getOneFallBack
3、service-provider的rest服务设个断点,即调用远程服务超过设置的超时时间(先读commanProperties,没配置再读yml文件配置)后,开始
调用getOneFallBack