Spring Cloud 学习第四章:服务消费者 ribbon 与 Feign 使用断路器 Hystrix

参考博客地址:https://blog.csdn.net/forezp/article/details/81040990

前言:前两章学习了 ribbon 和 Fegin 服务消费者,今天学习这两个消费者使用 Hystrix 做服务的熔断机制。

一、Hystrix 简介

Netflix 开源了 Hystrix 组件,实现了断路器模式,SpringCloud 对这一组件进行了整合。 在微服务架构中,一个请求需要调用多个服务是非常常见的。
如果较底层的服务如果出现故障,会导致连锁故障。当对特定的服务的调用的不可用达到一个阀值(Hystric 是5秒20次) 断路器将会被打开。
断路打开后,可用避免连锁故障,fallback方法可以直接返回一个固定值。

二、ribbon 中使用 Hystrix 断路器

1、打开之前创建的工程 eureka-server、eureka-client、eureka-ribbon 三个工程

2、eureka-ribbon 工程中加入此依赖

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

3、启动类中加入注解 : @EnableHystrix

4、测试方法
hello 方法上加上注解:@HystrixCommand ,该注解对该方法创建了熔断器的功能,并指定了 fallbackMethod 熔断方法 : error

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "error")// 此处error 指向下方 error 方法
     public String hello(String name){
        return restTemplate.getForObject("http://EUREKA-CLIENT/hello?name="+name,String.class);
    }


    public String error(String name){
        return "hi,"+name+",sorry,error!";
    }
}

5、启动三个工程:eureka-server、eureka-client、eureka-ribbon

访问:http://localhost:8764/hello

出现 :hello wxw , i am from port: 8762

6、关闭 eureka-client 工程

访问:http://localhost:8764/hello

出现 :hi,wxw,sorry,error!

此时,eureka-ribbon 已经无法访问到 eureka-client 开启的服务, 会执行快速失败,直接返回一组字符串,而不是等待响应超时,这很好的控制了容器的线程阻塞

三、Fegin 使用 Hystrix 熔断器

1、Feign是自带断路器的,在D版本的Spring Cloud之后,它没有默认打开。需要在配置文件中配置打开它,在 eureka-fegin 工程配置文件加以下代码:

# 开启 hystrix 熔断器
feign:
  hystrix:
    enabled: true

2、测试方法更改

增加实现类,实现 HelloService 接口,使用 @Component 注解注入到 IOC 容器

@Component
public class HelloServiceImpl implements  HelloService {
    @Override
    public String hello(String name) {
        return "hi : "+name+", sorry error!";
    }
}

3、接口类中方法更改注解
@FeignClient 中增加属性,fallback = HelloServiceImpl.class
指定熔断类

@Service
@FeignClient(value = "EUREKA-CLIENT",fallback = HelloServiceImpl.class)
public interface HelloService {


    @RequestMapping(value = "/hello")
    String hello(@RequestParam(value = "name") String name);
}

4、启动 eureka-fegin 工程

访问 : http://localhost:8765/hello

返回:hi : wxw, sorry error!

此时,因为 eureka-client 工程已经关闭,所以访问不到 接口服务,此时断路器起到了作用

启动 eureka-client 工程,再次访问

访问 : http://localhost:8765/hello

返回:hello wxw , i am from port: 8762

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值