Hystrix通用方式整合

返回目录

https://blog.csdn.net/BW_Bear/article/details/88746646

源码位置:

微服务注册管理:

https://github.com/zhaowei-zhang/CloudTest/tree/master/使用Hystrix实现容错/microservice-discovery-eureka

生产者:

https://github.com/zhaowei-zhang/CloudTest/tree/master/使用Hystrix实现容错/microservice-provider-user

通用方式整合:

https://github.com/zhaowei-zhang/CloudTest/tree/master/使用Hystrix实现容错/microservice-consumer-movie-ribbon-hystrix

1.依赖

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

2.启动类注解

添加
@EnableHystrix 或 @EnableCircuitBreaker
为项目添加断路器支持

3.修改Controller

方法增加容错注解,以及设定回退方法
@HystrixCommand(fallbackMethod = “findByIdFallback”)

fallbackMethod 设定回退方法名

@HystrixCommand(fallbackMethod = "findByIdFallback")
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id){
    return this.restTemplate.getForObject("http://microservice-provider-user/"+id,User.class);
}

public User findByIdFallback(Long id){
    User user =new User();
    user.setId(-1L);
    user.setName("游客");
    return user;
}

4.确定何种异常进行回退

ignoreExceptions 设定不进入回退的方法

@HystrixCommand(fallbackMethod = "findByIdFallback",ignoreExceptions = {
        IllegalArgumentException.class
})
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id){
    if(id==1){
        throw new IllegalArgumentException();
    }
    else if(id==2){
        throw new IndexOutOfBoundsException();
    }
    return this.restTemplate.getForObject("http://MICROSERVICE-PROVIDER-USER/"+id,User.class);
}

区别如下:

在这里插入图片描述
在这里插入图片描述

5.确定配置属性

commandProperties
在这里插入图片描述
属性配置可不写,详细配置请看
https://github.com/Netflix/Hystrix/wiki/Configuration

6.测试

见4中图片

返回目录

https://blog.csdn.net/BW_Bear/article/details/88746646

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值