009 SpringCloud 学习笔记5-----Hystrix保护机制

1.概述

Hystrix,英文意思是豪猪,全身是刺,看起来就不好惹,是一种保护机制
Hystrix也是Netflix公司的一款组件。
主页:https://github.com/Netflix/Hystrix/
Hystix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败。

2.雪崩问题

微服务中,服务间调用关系错综复杂,一个请求,可能需要调用多个微服务接口才能实现,会形成非常复杂的调用链路:

 

如图,一次业务请求,需要调用A、P、H、I四个服务,这四个服务又可能调用其它服务。

如果此时,某个服务出现异常:

 

例如微服务I发生异常,请求阻塞,用户不会得到响应,则tomcat的这个线程不会释放,于是越来越多的用户请求到来,越来越多的线程会阻塞:

服务器支持的线程和并发数有限,请求一直阻塞,会导致服务器资源耗尽,从而导致所有其它服务都不可用,形成雪崩效应

这就好比,一个汽车生产线,生产不同的汽车,需要使用不同的零件,如果某个零件因为种种原因无法使用,那么就会造成整台车无法装配,陷入等待零件的状态,直到零件到位,才能继续组装。  此时如果有很多个车型都需要这个零件,那么整个工厂都将陷入等待的状态,导致所有生产都陷入瘫痪。一个零件的波及范围不断扩大。

Hystix解决雪崩问题的手段有两个:(1)线程隔离 (2)服务熔断

3.线程隔离,服务降级

(1)线程隔离示意图:

 

Hystrix为每个依赖服务调用分配一个小的线程池,如果线程池已满调用将被立即拒绝,默认不采用排队.加速失败判定时间。

用户的请求将不再直接访问服务,而是通过线程池中的空闲线程来访问服务,如果线程池已满,或者请求超时,则会进行降级处理。

(2)服务降级:优先保证核心服务,而非核心服务不可用或弱可用。

用户的请求故障时,不会被阻塞,更不会无休止的等待或者看到系统崩溃,至少可以看到一个执行结果(例如返回友好的提示信息) 。
服务降级虽然会导致请求失败,但是不会导致阻塞,而且最多会影响这个依赖服务对应的线程池中的资源,对其它服务没有响应。
触发Hystix服务降级的情况:(1)线程池已满 (2)请求超时

4.入门案例

(1)引入依赖

首先在lucky-service-consumer的pom.xml中引入Hystrix依赖:

 

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

 

(2)开启熔断

(3)编写降级逻辑

我们改造lucky-service-consumer,当目标服务的调用出现故障,我们希望快速失败,给用户一个友好提示。因此需要提前编写好失败时的降级处理逻辑,要使用注解@HystixCommond来完成:

要注意,因为熔断的降级逻辑方法必须跟正常逻辑方法保证:相同的参数列表和返回值声明

package lucky.service.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lucky.service.domain.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Controller
@RequestMapping(path = "/consumer/user")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(path = "/queryUsersById")
    @ResponseBody
    @HystrixCommand(fallbackMethod = "queryUserByIdFallback")
    public String queryUserById(@RequestParam("id") Integer id){

        // 获取ip和端口信息,拼接成服务地址
        String baseUrl = "http://SERVICE-PROVIDER/users/queryUsersById?id=" + id;
        return this.restTemplate.getForObject(baseUrl, String.class);
    }

    public String queryUserByIdFallback(Integer id){
        return "服务正忙,请稍后再试";
    }


}

注意:@HystrixCommand(fallbackMethod = "queryByIdFallBack"):用来声明一个降级逻辑的方法

(4)测试

当lucky-service-provder正常提供服务时,访问与以前一致。但是当我们将lucky-service-provider停机时,会发现页面返回了降级处理信息:

<1>正常提供服务时

 

<2>lucky-service-provider停机时

(5)优化----默认FallBack

我们刚才把fallback写在了某个业务方法上,如果这样的方法很多,那岂不是要写很多。所以我们可以把Fallback配置加在类上,实现默认fallback:

package lucky.service.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lucky.service.domain.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Controller
@RequestMapping(path = "/consumer/user")
@DefaultProperties(defaultFallback = "fallBackMethod") // 指定一个类的全局熔断方法
public class UserController {
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(path = "/queryUsersById")
    @ResponseBody
    @HystrixCommand  // 标记该方法需要熔断
    public String queryUserById(@RequestParam("id") Integer id){

        // 获取ip和端口信息,拼接成服务地址
        String baseUrl = "http://SERVICE-PROVIDER/users/queryUsersById?id=" + id;
        return this.restTemplate.getForObject(baseUrl, String.class);
    }


    /**
     * 熔断方法
     * 返回值要和被熔断的方法的返回值一致
     * 熔断方法不需要参数
     * @return
     */
    public String fallBackMethod(){
        return "服务正忙,请稍后再试";
    }


}

- @DefaultProperties(defaultFallback = "defaultFallBack"):在类上指明统一的失败降级方法
- @HystrixCommand:在方法上直接使用该注解,使用默认的熔断方法。
- defaultFallback:默认降级方法,不用任何参数,以匹配更多方法,但是返回值一定一致

(6)设置超时

在之前的案例中,请求在超过1秒后都会返回错误信息,这是因为Hystix的默认超时时长为1,我们可以通过配置在lucky-service-consumer这个模块的yml文件中修改这个值:

我们可以通过hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds来设置Hystrix超时时间。该配置没有提示。

server:
  port: 8080
logging:
  level:
    root: info
spring:
  application:
    name: service-consumer #注册到eureka后的微服务的名称
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10086/eureka
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000 # 设置hystrix的超时时间为6000ms

 

posted @ 2019-09-03 16:24  雨后观山色  阅读(317)  评论(0编辑  收藏  举报