SpringCloud-hystrix

痛定思痛。 2021-10-06 03:02 402阅读 0赞

SpringCloud-hystrix简单使用

  • 引入依赖
  • 开启服务熔断
  • 编写服务

引入依赖

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  4. </dependency>

开启服务熔断

添加注解
@EnableFeignClients
@EnableCircuitBreaker

编写服务

在调用服务的方法上添加注解

  1. @GetMapping("/info")
  2. @HystrixCommand(fallbackMethod="defaultInfo")
  3. public String info(){
  4. //通过feign调用服务
  5. return infoDao.info(); //当远程服务不通,会走执行默认方法
  6. }
  7. public String defaultInfo(){
  8. return "Server is down! ";
  9. }

服务调用使用了Feign技术,可以使用更简洁方式实现熔断,如下:
但需要添加配置:feign.hystrix.enabled=true

  1. @FeignClient(name="service-test", fallback=InfoFallback.class)
  2. public interface InfoService {
  3. @GetMapping("/info/list")
  4. List<Info> info() throws Exception;
  5. @GetMapping("/info/{id}")
  6. RestResult getInfo(@PathVariable("id") String id);
  7. }
  8. @Component
  9. public class InfoFallback implements InfoService {
  10. @Override
  11. public List<Info> info() throws Exception {
  12. //**
  13. return info;
  14. }
  15. @Override
  16. public RestResult getInfo(String id) {
  17. return null;
  18. }
  19. }

发表评论

表情:
评论列表 (有 0 条评论,402人围观)

还没有评论,来说两句吧...

相关阅读