Spring Cloud熔断机制 -- 断路器

1. 熔断机制介绍

在介绍熔断机制以前,咱们须要了解微服务的雪崩效应。在微服务架构中,微服务是完成一个单一的业务功能,这样作的好处是能够作到解耦,每一个微服务能够独立演进。可是,一个应用可能会有多个微服务组成,微服务之间的数据交互经过远程过程调用完成。这就带来一个问题,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其它的微服务,这就是所谓的“扇出”。若是扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A的调用就会占用愈来愈多的系统资源,进而引发系统崩溃,所谓的“雪崩效应”。spring

 

a

熔断机制是应对雪崩效应的一种微服务链路保护机制。咱们在各类场景下都会接触到熔断这两个字。高压电路中,若是某个地方的电压太高,熔断器就会熔断,对电路进行保护。股票交易中,若是股票指数太高,也会采用熔断机制,暂停股票的交易。一样,在微服务架构中,熔断机制也是起着相似的做用。当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后,恢复调用链路。架构

二、实战

1. 在maven工程(前面章节中介绍的Ribbon或者Feign工程)的pom.xml中添加hystrix库支持断路器

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

2. 在Ribbon应用中使用断路器

在Spring Boot启动类上添加@EnableCircuitBreaker注解app

1 @SpringBootApplication
2 @EnableDiscoveryClient
3 @EnableCircuitBreaker
4 public class ServiceRibbonApplication {
5 
6     public static void main(String[] args) {
7         SpringApplication.run(ServiceRibbonApplication.class, args);
8     }
。。。 。。。

三、 在Feign应用中使用断路器maven

1). Feign内部已经支持了断路器,因此不须要想Ribbon方式同样,在Spring Boot启动类上加额外注解ide

2). 用@FeignClient注解添加fallback类, 该类必须实现@FeignClient修饰的接口。微服务

1 @FeignClient(name = "SERVICE-HELLOWORLD", fallback = HelloWorldServiceFailure.class)
2 public interface HelloWorldService {
3     @RequestMapping(value = "/", method = RequestMethod.GET)
4     public String sayHello();
5 }

3). 建立HelloWorldServiceFailure类, 必须实现被@FeignClient修饰的HelloWorldService接口。注意添加@Component或者@Service注解,在Spring容器中生成一个Beanui

复制代码

1 @Component
2 public class HelloWorldServiceFailure implements HelloWorldService {
3     @Override
4     public String sayHello() {
5         System.out.println("hello world service is not available !");
6         return "hello world service is not available !";
7     }
8 }

复制代码

相关文章
相关标签/搜索