熔断器-Hystrix。。。之降级方法

2022-10-22,,,

与Feign的Fallback降级方法不同,这个hystrix降级方法是写在被调用方的

需要依赖:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

启动类需要注解:例如

@SpringBootApplication
@EnableEurekaClient
//开启Hystrix
@EnableCircuitBreaker
public class SearchApplication { public static void main(String[] args) {
SpringApplication.run(SearchApplication.class, args);
}
}

在controller中,针对某一个接口去写降级方法,例如

@RestController
public class SearchController { /**
* 模拟根据id查询
* 注解里指定了接口发生异常后, 降低调用的方法
* @param id
*/
@GetMapping("/search/{id}")
@HystrixCommand(fallbackMethod = "findByIdFallBack")
public Customer findById(@PathVariable Integer id){
int i = 1/0;
return new Customer(1,"张三",23);
} /**
* findById的降级方法 方法的描述要和接口一致
* 一致是指和原接口方法, 传参, 返回值必须要一模一样
*/
public Customer findByIdFallBack(Integer id){
return new Customer(-1,"",0);
}
}

简单的hystrix降级方法,就OK了

熔断器-Hystrix。。。之降级方法的相关教程结束。

《熔断器-Hystrix。。。之降级方法.doc》

下载本文的Word格式文档,以方便收藏与打印。