<version>2.2.10.RELEASE</version></dependency>
#### 配置启动类在启动类中使用 `@EnableCircuitBreaker` 注解开启断路器功能
@SpringBootApplication
// 激活EurekaClient
@EnableEurekaClient
//激活Hystrix
@EnableCircuitBreaker
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
#### 添加熔断机制在服务消费者的方法上添加注解`@HystrixCommand(fallbackMethod="handleTimeout")`,其中fallbackMethod中指定的是服务降级后处理的函数。当在指定的时间里没有响应时,便会回调handle函数。响应时间默认为1000ms,可以通过commandProperties来指定,例如将响应时间设为1500ms,`@HystrixCommand(fallbackMethod = "handleTimeout",commandProperties = { @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "1500") })`。
@GetMapping(value = "/buy/{id}")
//@HystrixCommand(fallbackMethod = "handleTimeout")
@HystrixCommand(fallbackMethod = "handleTimeout",commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "1500")
})
public Product findById(@PathVariable Long id) {Product product = null;URI uri = null;try {uri = new URI("http://service-product/product/" + id);} catch (URISyntaxException e) {e.printStackTrace();}//这里故意弄一个超时,强迫其服务降级try {Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();}product = restTemplate.getForObject(uri, Product.class);return product;
}
#### 服务降级有两种情况可以导致服务降级,一种是调用服务时超时,另一种是调用服务时抛出异常。##### 超时调用服务提供者的方法超时时,Hystrix机制便会进行服务降级,通过回调@HystrixCommand中fallbackMethod指定的函数来进行降级,这种方法虽然得不到用户想要的结果,但保证了服务的可用性,不至于造成雪崩现象。这里需要注意此函数的**返回值以及参数列表**需要与添加熔断的方法保持一致。接上面的代码,这里给出handleTimeout方法。
public Product handle(Long id) {Product product = new Product();product.setId(0L);product.setName("A fake product");product.setPrice(new BigDecimal(0));return product;
}
运行结果 :
{
“id”: 0,
“name”: “A fake product”,
“price”: 0
}
**注意**:超时不管发生在服务调用方,还是服务提供者方都会进行服务降级。针对上面的两段代码,在服务消费者的方法findById上添加的熔断机制,findById中调用了服务提供者的方法 http://service-product/product/{id}, 不管在哪个方法中发生了超时,都会回调handleTimeout方法。##### 异常当调用服务时发生了异常,默认情况下也是回调服务降级函数,如果在发生异常时不想进行服务降级,可以在@HystrixCommand添加`ignoreExceptions = Exception.class` 。例如: **异常服务降级**:
@GetMapping(value = "/buy1/{id}/{price}")
@HystrixCommand(fallbackMethod = "handleException")
public Product findByIdAndPrice1(@PathVariable Long id, @PathVariable BigDecimal price) {Product product = null;// 这里故意弄一个运行时异常超时,强迫其服务降级int i = 1 / 0;product = restTemplate.getForObject("http://service-product/product/{1}/{2}", Product.class, id, price);return product;
}public Product handleException(Long id, BigDecimal price, Throwable throwable) {Product product = new Product();product.setId(0L);product.setName(throwable.getMessage());product.setPrice(new BigDecimal(0));return product;
}
运行结果:
{
“id”: 0,
“name”: “/ by zero”,
“price”: 0
}
**异常服务不降级**: 当将注解改成:`@HystrixCommand(fallbackMethod = "handleException", ignoreExceptions = Exception.class)`时,最终的运行结果为:
{
“timestamp”: “2022-05-24T14:57:00.759+0000”,
“status”: 500,
“error”: “Internal Server Error”,
“message”: “/ by zero”,
“path”: “/order/buy1/1/8000”
}
后端log为:
java.lang.ArithmeticException: / by zero