SpringCloud微服务架构搭建(四):断路器

在Spring Cloud中使用了Hystrix 来实现断路器的功能。Hystrix是Netflix开源的微服务框架套件之一,该框架目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix具备拥有回退机制和断路器功能的线程和信号隔离,请求缓存和请求打包,以及监控和配置等功能。

一、ribbon中使用hystrix

这里继续使用上一篇的client-a。

1.1
pom文件添加hystrix

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

1.2
ClientApplication添加@EnableHystrix开启hystrix功能

1.3
Controller, 使用@HystrixCommand指定回调方法

@RestController
public class TestController {

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("/hi")
    @HystrixCommand(fallbackMethod = "hiFallback")
    public String hi(@RequestParam String id){
        return restTemplate.getForObject("http://service-a/hi?id="+id, String.class);
    }

    public String hiFallback(String id) {
        return "hi, " + id + ", error!";
    }
}

1.4
启动client-a, 然后关闭service-a, 打开页面

可以看到成功返回错误信息,实现断路回调。

二、feign中使用hystrix

2.1
feign是自带断路器功能的,并且默认打开,如果你要关闭的话,需要加上这个配置:

feign:
    hystrix:
        enabled: false

2.2
这里只需要在@FeignClient注解上加上fallback就可以了

@Component
@FeignClient(value = "service-a", fallback = ServiceAFeignClientFallback.class) //这里的value对应服务的spring.applicatoin.name
public interface ServiceAFeignClient {

    @RequestMapping(value = "/hi")
    String hi(@RequestParam("id") String id);

}

ServiceAFeignClientFallback:

@Component
public class ServiceAFeignClientFallback implements ServiceAFeignClient {

    @Override
    public String hi(String id) {
        return "hi, " + id + ", error!";
    }

}注意ServiceAFeignClientFallback类要加上component注解,不然会报下面的错误Caused by: Java.lang.IllegalStateException: No fallback instance of type class 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值