前面文中我们学习了hystrix的原生使用(hystrix入门-原生API使用)和注解使用(hystrix进阶-注解hystrix-javanica使用),本文来看下hystrix在spring-boot中的使用。
首先还是先看个最简单的demo
第一步:添加依赖
<dependency> <groupId>org.springframework.cloudgroupId> <artifactId>spring-cloud-starter-netflix-hystrixartifactId>dependency>
第二步:开启配置
在配置类上添加@EnableCircuitBreaker注解
@SpringBootApplication@EnableCircuitBreaker//添加这个注解public class HystrixBootApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixBootApplication.class, args); }}
第三步:在需要开启熔断降级的方法上添加@HystrixCommand
@RestControllerpublic class DemoController {
@HystrixCommand(fallbackMethod = "helloFallback") @GetMapping("/hello") public String hello(String msg){
throw new RuntimeException("hello throw RuntimeException"); } public String helloFallback(String msg, Throwable t) {
return "helloFallback:" + msg + "," + t.getMessage(); }}
浏览器访问:http://localhost:8080/hello?msg=world,输出结果:helloFallback:world,hello throw RuntimeException
异常传播
@HystrixCommand(fallbackMethod = "helloFallback")@GetMapping("/hello")public String hello(){
throw new HystrixBadRequestException("参数校验异常");}
只要抛出HystrixBadRequestException即可,就不会进入到fallback中。但是这样不太友好,业务代码跟hystrix耦合到了一起,两种解决办法:
第一种办法:可以让我们自定义的业务异常继承HystrixBadRequestException:
public static class BizException extends HystrixBadRequestException{
public BizException(String message) {
super(message); } public BizException(String message, Throwable cause) {
super(message, cause); }}
第二种办法:可以在@HystrixCommand上配置ignoreExceptions:
@HystrixCommand(fallbackMethod = "helloFallback", ignoreExceptions = ParamException.class)@GetMapping("/world")public String world(){
throw new ParamException("参数不能为空");}
熔断
@Res