服务器熔断Hystrix组件_Spring_cloud_5

一.服务容错的核心知识

1.1雪崩效应

在微服务架构中,一个请求需要调用多个服务是非常常见的。
如客户端访问A服务,而A服务需要调用B服务,B服务需要调用C服务,由于网络原因或者自身的原因,
如果B服务或者C服务不能及时响应,A服务将处于阻塞状态,直到B服务C服务响应。
此时若有大量的请求涌入,容器的线程资源会被消耗完毕,导致服务瘫痪。
服务与服务之间的依赖性,故障会传播,造成连锁反应,会对整个微服务系统造成灾难性的严重后果,
这就是服务故障的“雪崩”效应。

在这里插入图片描述
雪崩是系统中的蝴蝶效应导致其发生的原因多种多样,有不合理的容量设计,或者是高并发下某一个方
法响应变慢,亦或是某台机器的资源耗尽。从源头上我们无法完全杜绝雪崩源头的发生,但是雪崩的根
本原因来源于服务之间的强依赖,所以我们可以提前评估,做好
熔断,隔离,限流

1.2.解决雪崩效应的方式

1.2.1 服务隔离

顾名思义,它是指将系统按照一定的原则划分为若干个服务模块,各个模块之间相对独立,无强依赖。当有故障发生时,能将问题和影响隔离在某个模块内部,而不扩散风险,不波及其它模块,不影响整体的系统服务。

1.2.2 熔断降级

熔断这一概念来源于电子工程中的断路器(Circuit Breaker)。在互联网系统中,当下游服务因访问压力过大而响应变慢或失败,上游服务为了保护系统整体的可用性,可以暂时切断对下游服务的调用。这种牺牲局部,保全整体的措施就叫做熔断。
所谓降级,就是当某个服务熔断之后,服务器将不再被调用,此时客户端可以自己准备一个本地的fallback回调,返回一个缺省值。 也可以理解为兜底

1.2.3 服务限流

限流可以认为服务降级的一种,限流就是限制系统的输入和输出流量已达到保护系统的目的。一般来说系统的吞吐量是可以被测算的,为了保证系统的稳固运行,一旦达到的需要限制的阈值,就需要限制流量并采取少量措施以完成限制流量的目的。比方:推迟解决,拒绝解决,或者者部分拒绝解决等等。

二.Hystrix介绍

Hystrix是由Netflix开源的一个延迟和容错库,用于隔离访问远程系统、服务或者第三方库,防止级联失败,从而提升系统的可用性与容错性。Hystrix主要通过以下几点实现延迟和容错。
  • 包裹请求:使用HystrixCommand包裹对依赖的调用逻辑,每个命令在独立线程中执行。这使用 了设计模式中的“命令模式”。
  • 跳闸机制:当某服务的错误率超过一定的阈值时,Hystrix可以自动或手动跳闸,停止请求该服务 一段时间。
  • 资源隔离:Hystrix为每个依赖都维护了一个小型的线程池(或者信号量)。如果该线程池已满,发往该依赖的请求就被立即拒绝,而不是排队等待,从而加速失败判定。
  • 监控:Hystrix可以近乎实时地监控运行指标和配置的变化,例如成功、失败、超时、以及被拒绝 的请求等。
  • 回退机制:当请求失败、超时、被拒绝,或当断路器打开时,执行回退逻辑。回退逻辑由开发人员 自行提供,例如返回一个缺省值。
  • 自我修复:断路器打开一段时间后,会自动进入“半开”状态。

三.基于RestTemplate实现服务熔断

具体操作步骤:在服务消费方的代码中

1.1 引入Hystrix的依赖

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

1.2 在启动类上激活Hystrix

添加注解:@EnableCircuitBreaker
在这里插入图片描述

1.3 配置熔断触发的降级逻辑

/**
     * 降级方法
     *  和需要受到保护方法的返回值一致
     *  方法参数一致
     */
    public Product orderFallBack(Long id){
        Product product = new Product();
        product.setProductName("触发服务降级方法");
        return product;
    }

1.4 在需要受到保护的接口上使用 @HystrixCommand注解配置

注解括号内写的fallbackMethod值为1.3声明的降级方法名称

 /**
     * 基于ribbon的形式调用远程服务
     *  1.使用@LoadBalanced声明Restemplate
     *  2.使用服务名称替换ip地址
     *  3.添加熔断保护注解
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "orderFallBack")
    @RequestMapping(value = "/buyRibbon/{id}",method = RequestMethod.GET)
    public Product findByIdRibbon(@PathVariable Long id){
        
        Product product = restTemplate.getForObject("http://service-product/product/1",Product.class);
        return product;
    }

1.5 hystrix的熔断降级时间默认为1秒,可以通过配置来延长

在application.yml中配置如下内容即可:
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000 #默认的连接超时时间为1秒,若1秒没有返回数据,自动的触发降级逻辑

1.6 降级方法返回的统一配置

1.6.1 在类中先声明一个统一的返回方法

    /**
     * 统一的降级方法
     *  方法没有参数
     */
    public Product defaultFallBack(){
        Product product = new Product();
        product.setProductName("触发统一服务降级方法");
        return product;
    }

1.6.2 在被保护的方法上加入不带参数的注解@HystrixCommand

  /**
     * 基于ribbon的形式调用远程服务
     *  1.使用@LoadBalanced声明Restemplate
     *  2.使用服务名称替换ip地址
     *  3.添加熔断保护注解
     * @param id
     * @return
     */
   // @HystrixCommand(fallbackMethod = "orderFallBack")
    @HystrixCommand
    @RequestMapping(value = "/buyRibbon/{id}",method = RequestMethod.GET)
    public Product findByIdRibbon(@PathVariable Long id){
        
        Product product = restTemplate.getForObject("http://service-product/product/1",Product.class);
        return product;
    }

1.6.3 在类上面的添加注解@DefaultProperties(defaultFallback = “defaultFallBack”)
其中参数为刚才声明的统一的方法

package order.controller;


import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import order.entity.Product;
import order.feign.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/order")
/**
 * @DefaultProperties:指定此接口中公共的熔断设置
 *          如果在@DefaultProperties指定了公共的降级方法
 *          在方法上的 @HystrixCommand不需要单独指定了
 */
@DefaultProperties(defaultFallback = "defaultFallBack")
public class OrderController {

    @Autowired
    private  RestTemplate restTemplate;
    //注入使用feign的接口
    @Autowired
    private ProductFeignClient productFeignClient;





    /**
     * 基于ribbon的形式调用远程服务
     *  1.使用@LoadBalanced声明Restemplate
     *  2.使用服务名称替换ip地址
     *  3.添加熔断保护注解
     * @param id
     * @return
     */
   // @HystrixCommand(fallbackMethod = "orderFallBack")
    @HystrixCommand
    @RequestMapping(value = "/buyRibbon/{id}",method = RequestMethod.GET)
    public Product findByIdRibbon(@PathVariable Long id){
        
        Product product = restTemplate.getForObject("http://service-product/product/1",Product.class);
        return product;
    }
    /**
     * 统一的降级方法
     *  方法没有参数
     */
    public Product defaultFallBack(){
        Product product = new Product();
        product.setProductName("触发统一服务降级方法");
        return product;
    }

    /**
     * 降级方法
     *  和需要受到保护方法的返回值一致
     *  方法参数一致
     */
    public Product orderFallBack(Long id){
        Product product = new Product();
        product.setProductName("触发服务降级方法");
        return product;
    }


}

四. Feign实现服务熔断

1.1引入依赖

feign中已经支持了Hystrix,因此可以不用引用

在这里插入图片描述

1.2 配置启用hystrix

在application.yml配置文件中增加如下配置:

feign:
  hystrix:
    enabled: true

1.3 编写feign接口的实现类,处理熔断降级的逻辑

此类中注意返回的对象与类中的注解@Component,注入到容器中去

package order.feign;

import order.entity.Product;
import org.springframework.stereotype.Component;

@Component
public class ProductFeignClientCallBack implements ProductFeignClient{

    public Product findById(Long id) {
        Product product = new Product();
        product.setProductName("基于feign的熔断方法");
        return product;
    }
}

1.4 在feign的接口的注解中增加属性

@FeignClient(name = “service-product”,fallback = ProductFeignClientCallBack.class)
其中fallback的值为刚才1.3的实现类

package order.feign;


import order.entity.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 声明需要调用的微服务名称
 * @FeignClient
 *      name:服务提供者的名称
 */
@FeignClient(name = "service-product",fallback = ProductFeignClientCallBack.class)
public interface ProductFeignClient {

    /**
     * 配置需要调用的微服务接口
     * @param id
     * @return
     */
    @RequestMapping(value = "/product/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable("id")Long id);
}

1.5 hystrix的熔断降级时间默认为1秒,可以通过配置来延长

在application.yml中配置如下内容即可:
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000 #默认的连接超时时间为1秒,若1秒没有返回数据,自动的触发降级逻辑
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值