Spring Cloud 入门——2.1 Hystrix 熔断器服务降级

24 篇文章 0 订阅
22 篇文章 3 订阅

代码信息

本篇文章涉及代码版本

组件版本
Spring Boot2.0.8.RELEASE
Spring CloudFinchley.SR1

本篇文章涉及应用

应用说明
base-eureka服务发现
base-hystrix熔断器

整合熔断器

Hystrix熔断器,容错管理工具,旨在通过熔断机制控制服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。

构建maven依赖

熔断器的其他配置可以参照服务提供方的配置,然后只需要新增hystrix的依赖

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

application.yml

application配置甚至不需要怎么修改

spring:
  application:
    name: base-hystrix
server:
  port: 8404

eureka:
  client:
    service-url: 
      defaultZone: http://localhost:8000/eureka/
logging:
  file: ${spring.application.name}.log

类的配置

启动类

和之前的应用相比需要添加@EnableCircuitBreaker注解

@EnableEurekaClient
@SpringBootApplication
@EnableCircuitBreaker
public class HystrixApplication {

    public static void main(String[] args) {
        SpringApplication.run(HystrixApplication.class, args);
    }
}

远程调用和类降级

此时需要我们一个方法用来请求数据,以及和它对应的降级方法。我们请求测试的base-producer应用的接口

@Log
@Service
public class ClientService {

    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Autowired
    RestTemplate restTemplate;

    /**
     * 配置降级方法
     * @return
     */
    @HystrixCommand(fallbackMethod = "getServiceBack")
    public String getService() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("base-producer");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/getService";
        log.info(url);
        return restTemplate.postForObject(url,null, String.class);
    }


    public String getServiceBack() {
        return "use fallbackMethod";
    }
    
}

测试用的请求类

现在我们编写一个controller稍后来测试我们的服务降级是否发挥作用

@Log
@RestController
public class HystrixController {

    @Autowired ClientService clientService;

    @RequestMapping(value = "/hystrixGetService",method = RequestMethod.GET)
    public String getService() {
        return clientService.getService();
    }
    
}

测试

  1. 首先我们依次启动 base-eureka,base-producer,base-hystrix三个服务

在这里插入图片描述

  1. 然后我们请求base-hystrix的hystrixGetService接口,此时返回结果正确

在这里插入图片描述
3. 然后我们停掉base-producer再次请求

在这里插入图片描述

此时可以发现返回的就是之前服务降级配置的内容,证明服务降级已经生效。


本篇文章涉及的源码下载地址:https://gitee.com/daifylearn/cloud-learn

ps.上述的所有项目都是可以成功运行的。但是在后期为了实现每个应用端口尽量不冲突会有些许调整,而后续某次作死调整结构和名称可能会导致部分项目无法运行o(╯□╰)o,如果发现请留言我进行修改。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大·风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值