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.依赖



    org.springframework.cloud
    spring-cloud-starter-netflix-hystrix

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);
}

区别如下:

Hystrix通用方式整合_第1张图片
Hystrix通用方式整合_第2张图片

5.确定配置属性

commandProperties
Hystrix通用方式整合_第3张图片
属性配置可不写,详细配置请看
https://github.com/Netflix/Hystrix/wiki/Configuration

6.测试

见4中图片

返回目录

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

你可能感兴趣的:(SpringCloud)