好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解spring cloud分布式关于熔断器

spring cloud 分布式 中,熔断器就是断路器,其实都是一个意思。

为什么要使用熔断器呢?

在分布式中,我们会根据业务或功能将项目拆分为多个服务单元,各个服务单元之间通过服务注册和订阅的方式相互依赖和调用功能,随着项目和业务的不断拓展,服务单元数量也逐渐增多,相互之间的依赖关系也越来越复杂,这时候,可能会某个服务单元出现问题或网络原因依赖调用出错或延迟,此时如果调用该依赖的请求不断增加,那么要调用该服务的服务将都会等待或者出现故障,如果后续连锁反应越来越多,servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务的依赖会导致服务之间的故障传播,从而迎来[雪崩效应[。为了解决这种每个点或多个点的故障,就有了熔断器的出现。

什么是熔断器?

熔断器就相当于电路中的保险丝、保护器,它可以实现快速失败,如果它在某一段时间里侦测到许多类似的错误,它将不再访问远程服务器,会强迫以后的访问都会快速失败,从而防止某个服务不断地尝试执行可能会失败的操作,它会使服务继续执行而不用等待修正错误,或者浪费cpu时间去等到长时间的超时产生,从而进入回路方法。熔断器也可以使服务能够诊断错误是否已经修正,如果已经修正,服务会再次尝试调用操作。

1.在调用服务方加入熔断器依赖jar包:

?

1

2

// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix

  compile group: 'org.springframework.cloud' , name: 'spring-cloud-starter-hystrix'

2.在controller中:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

@controller

//@enablewebsecurity 安全检查controller还要继承extends websecurityconfigureradapter

public class pagecontroller  {

 

   public static logger logger=loggerfactory.getlogger(pagecontroller. class );

 

   @autowired

   private resttemplate resttemplate;

 

 

   @hystrixcommand (fallbackmethod = "toindex1" ) //断路器进入回路方法

   @requestmapping ( "/toindex1" )

   public string toindex(model model){

 

     system.out.println( "进入toindex" );

     logger.info( "执行调用" );

     string msg=resttemplate.getforentity( "http://project-solr/solrsearch" ,string. class ).getbody();//project-solr是调用注册中心里的名字

     logger.info( "调用结束" );

     model.addattribute( "msg" ,msg);

     return "index" ;

   }

 

   public string toindex1(model model){

     system.out.println( "进入回路方法" );

     model.addattribute( "msg" , "服务不可用,请稍后重试" );

     return "index" ;

   }

}

注意:在调用方服务controller中的方法上加上@hystrixcommand(fallbackmethod = "回路方法")

这里我让回路方法调用的是toindex1,要注意回路方法返回值,参数要与原方法一致

在被调用方的方法中制造故障:

3.在调用方的启动类加注解@enablecircuitbreaker启动熔断器

启动:

可以看到进入了回路方法

当然还可以在调用方进行配置:

?

1

2

3

4

5

6

7

8

9

10

11

hystrix:

  command:

   default :

    execution:

    isolation:

     thread:

      timeoutinmilliseconds: 2000 #请求响应时间 如果过了这个时间就会进入回路方法

    circuitbreaker:

      requestvolumethreshold: 2 # 服务降级:此请求连续多少次响应过慢或崩溃 系统就默认把它当成一个崩溃的方法 在一定时间内调用此方法会直接进入回路方法 这样执行更快 默认值是 20 请求该方法 20 次 如果崩溃或响应过慢率大于百分之八十 就会默认它是一个崩溃方法

      #timeout:

        #enabled: false #取消超时检查 无论线程运行多久 只要不崩溃就不进入回路方法 一般情况不使用

配置完后运行:

运行好几次发现它会前两次会访问并等待相应结果,后面不再访问就直接回应结果进入回路方法

当然这是根据配置:

spring cloud熔断器就说到这里,想了解spring cloud其他内容,请浏览我以前博客

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:http://www.cnblogs.com/itgaofei/p/9436849.html

查看更多关于详解spring cloud分布式关于熔断器的详细内容...

  阅读:45次