14SpringCloud - 断路器项目示例(Ribbon Hystrix)

在 Ribbon中使用断路器

添加依赖

在项目pom 加上hystrix的依赖

<!-- hystrix 断路器 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

服务注册

在程序的启动类RibbonConsumerApplication 通过 @EnableHystrix开启Hystrix 断路器监控

@EnableHystrix
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumerApplication.class, args);
    }
}

消费提供者方法

修改 ConsumerController 类的,hello 方法,加上注解@HystrixCommand(fallbackMethod = "defaultStores") 该注解对该方法创建了熔断器的功能 ,并指定了defaultStores熔断方法,熔断方法直接返回了一个字符串, "feign + hystrix ,提供者服务挂了"

@HystrixCommand表明该方法为hystrix包裹,可以对依赖服务进行隔离、降级、快速失败、快速重试等等hystrix相关功能 该注解属性较多,下面讲解其中几个

  • fallbackMethod 降级方法
  • commandProperties 普通配置属性,可以配置HystrixCommand对应属性,例如采用线程池还是信号量隔离、熔断器熔断规则等等
  • ignoreExceptions 忽略的异常,默认HystrixBadRequestException不计入失败
  • groupKey() 组名称,默认使用类名称
  • commandKey 命令名称,默认使用方法名
/**
 * 描述:调用提供者的 `home` 方法
 *
 **/
@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;
    @HystrixCommand(fallbackMethod = "defaultStores")
    @GetMapping(value = "/hello")
    public String hello() {
        return restTemplate.getForEntity("http://eureka-provider/", String.class).getBody();
    }

    public String defaultStores() {
        return "Ribbon + hystrix ,提供者服务挂了";
    }
}

测试断路器

依次启动项目:
spring-cloud-eureka-service
spring-cloud-eureka-provider-1
spring-cloud-eureka-provider-2
spring-cloud-eureka-provider-3
spring-cloud-ribbon-consumer-hystrix

启动该工程后,访问服务注册中心,查看服务是否都已注册成功:http://localhost:8761/
在这里插入图片描述

在命令窗口curl http://localhost:9000/hello,发现一切正常

或者浏览器get 请求http://localhost:9000/hello F5 刷新
在这里插入图片描述
停止 spring-cloud-eureka-provider-1 提供者,端口为:8081服务

再次访问命令窗口curl http://localhost:9000/hello,断路器已经生效,提示:Ribbon + hystrix ,提供者服务挂了。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值