zoukankan      html  css  js  c++  java
  • 第三篇:断路器(Hystrix)(Feign中使用断路器)

    在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用。为了保证其高可用,单个服务通常会集群部署。由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。

    为了解决这个问题,业界提出了断路器模型。

    一  断路器简介

    Netflix开源了Hystrix组件,实现了断路器模式,SpringCloud对这一组件进行了整合。 在微服务架构中,一个请求需要调用多个服务是非常常见的,如下图:

     较底层的服务如果出现故障,会导致连锁故障。当对特定的服务的调用的不可用达到一个阀值(Hystric 是5秒20次) 断路器将会被打开。

     

     断路打开后,可用避免连锁故障,fallback方法可以直接返回一个固定值。

    二  准备工作

    继续上一章的工程,启动eureka-server,callcenter-freeswitch

    三  Feign中使用断路器

    Feign是自带断路器的,在D版本的Spring Cloud之后,它没有默认打开。需要在配置文件中配置打开它,在application.yml配置文件加以下代码:

    feign:
      hystrix:
        enabled: true

    继续改造callcenter-user

      上次说到我们要调用callcenter-freeswitch服务里面的接口:

    需要加此注解@FeignClient(value = "callcenter-freeswitch")
    现在改为  @FeignClient(value = "callcenter-freeswitch",fallback =FreeswitchServiceHystric.class)
    package com.hmzj.callcenteruser.service;
    
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.stereotype.Service;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    
    /**
     * @author Yangqi.Pang
     * @version V0.0.1
     */
    @FeignClient(value = "callcenter-freeswitch",fallback =FreeswitchServiceHystric.class)
    @Service
    public interface FreeswitchService {
    
        @GetMapping("/test/sayHi/{userName}")
        String sayHi(@PathVariable(value = "userName") String userName);
    }

    那么我们再来看一下FreeswitchServiceHystric

    package com.hmzj.callcenteruser.service;
    
    import org.springframework.stereotype.Component;
    
    /**
     * @author Yangqi.Pang
     * @version V0.0.1
     */
    @Component
    public class FreeswitchServiceHystric implements FreeswitchService {
        @Override
        public String sayHi(String userName) {
            return "sorry "+userName+" callcenter-freeswitch error";
        }
    }

    下来只启动 eureka-server 和 callcenter-user  注意还没有启动callcenter-freeswitch

    下来访问 http://localhost:8051/test/freeswitchSayHi/pyq

     

    说明断路器起作用了  当callcenter-freeswitch还未启动时 callcenter-user 调用了callcenter-freeswitch 服务 如果没有  fallback 就会报错   如今有了断路器 妈妈再也不用担心我调用其他服务了!

    再次启动callcenter-freeswitch

     

  • 相关阅读:
    分分钟提升命令行模式下密码输入逼格
    MySQL server has gone away 的两个最常见的可能性
    第一次遇到刷新缓冲区延时
    Mac上安装mysqlclient的报错
    python3 --- locale命名空间让程序更加安全了
    doctest --- 一个改善python代码质量的工具
    MySQL优化器 --- index_merge
    机智的MySQL优化器 --- is null
    Centos-7.x 下子网掩码的配置
    JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(三):两个Viewmodel搞定增删改查
  • 原文地址:https://www.cnblogs.com/pangyangqi/p/9391184.html
Copyright © 2011-2022 走看看