Hystrix服务熔断基础操作

步骤一:

添加Pom依赖:

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.6.RELEASE</version>
</dependency>

步骤二:

  • 在启动类中添加对熔断的支持
//启动类
@SpringBootApplication
@EnableEurekaClient //自动在服务启动后自动注册到eureka中
@EnableDiscoveryClient //服务发现
@EnableCircuitBreaker//添加对熔断的支持
public class DeptProviderHystrix_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProviderHystrix_8001.class,args);
    }
}

步骤二:

举例:

@RestController //JSON格式传输,直接RestController
public class DeptController {
   @Autowired
    private DeptService deptService;

    @GetMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGet")//回退的方法
    public Dept get(@PathVariable("id") Integer id){
        Dept dept = deptService.queryById(id);
        if(dept==null){
            throw new RuntimeException("Id=>"+id+",不存在该用户,或信息无法找到~");
        }
        return dept;
    }


   //备选方案
   public Dept hystrixGet(@PathVariable("id") Integer id){
       return new Dept().setDeptno(id)
               .setDname("id=>"+id+"没有对应的信息,null-@Hystrix")
               .setDb_source("no this database in MySQL");
      //return new Dept().setDeptno(id)
   }
}

当服务出错时,会执行下面的方法区返回值给前台,避免服务报错,影响前台显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值