• 第三篇:断路器(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

     

  • 相关阅读:
    [LintCode] Set Matrix Zeros
    [LintCode] Identify Celebrity
    [LintCode] Edit Distance
    [LintCode] Edit Distance II
    [LintCode] Strings Serialization
    二十七. Keepalived热备 Keepalived+LVS 、 HAProxy服务器
    二十六. 集群及LVS简介 LVS-NAT集群 LVS-DR集群
    二十五 存储技术与应用 iSCSI技术应用 、 udev配置 NFS网络文件系统 、 Multipath多路径 、 NFS网络文件系统 、 udev配置
    二十三.Subversion基本操作、使用Subversion协同工作、制作nginx的RPM包
    二十二. 安装部署Tomcat服务器、使用Tomcat部署虚拟主机、使用Varnish加速Web
  • 原文地址:https://www.cnblogs.com/pangyangqi/p/9391184.html
Copyright © 2020-2023  润新知