• 使用熔断器防止服务雪崩


    概述

    //这儿引用李卫民的一段概述

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

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

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

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

    熔断器打开后,为了避免连锁故障,通过 fallback 方法可以直接返回一个固定值。

    Ribbon中使用熔断器

    在pom.xml中增加依赖

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

           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-ribbon</artifactId>
           </dependency>
           
    <!--主要引入hystrix断路器依赖-->
           <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-hystrix</artifactId>
           </dependency>

    在Application启动类增加@EnableCircuitBreaker注解

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.client.RestTemplate;

    @EnableDiscoveryClient
    @EnableCircuitBreaker
    @SpringBootApplication
    public class HystrixApplication {

       @Bean
       @LoadBalanced
       public RestTemplate restTemplate() {
           return new RestTemplate();
      }

       public static void main(String[] args) {
           SpringApplication.run(HystrixApplication.class, args);
      }
    }

    在Service中方法增加@HystrixCommand注解,标注这个方法是通过hystrix处理

    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
    import com.netflix.hystrix.exception.HystrixBadRequestException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.web.client.RestTemplate;

    @Service("helloService")
    public class HelloService {

       @Autowired
       private RestTemplate restTemplate;


       //fallbackMethod属性:指定断路器生效的执行方法
       @HystrixCommand(fallbackMethod = "helloFallBack",ignoreExceptions = {HystrixBadRequestException.class})
       public String hello() {
           return restTemplate.getForObject("http://eureka-provider/hello",
                   String.class);
      }

       protected String helloFallBack(){
           return "hello fall back";
      }
    }

    Controller层


    import com.ley.springcloud.hystrix.service.HelloService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    @RequestMapping("/api")
    public class HelloController {

       @Autowired
       @Qualifier("helloService")
       private HelloService helloService;


       @GetMapping("/hystrix/ribbon/hello")
       public String hell() {
           return helloService.hello();
      }
    }

    application.yml文件

    server:
    port: 8704

    spring:
    application:
      name: eureka-ribbon-hystrix
    cloud:
    #开启spring cloud的断路器支持
      circuit:
        breaker:
          enabled: true

    eureka:
    client:
      serviceUrl:
        defaultZone: http://localhost:1111/eureka/
    instance:
      lease-renewal-interval-in-seconds: 10 #服务续约
      lease-expiration-duration-in-seconds: 15 #服务剔除>服务续约时间
      instance-id: ${spring.application.name}:${server.port}
      hostname: localhost

    测试熔断器

    关闭服务提供者,再次请求http://localhost:8704/api/hystrix/ribbon/hello浏览器显示

    hello fall back

    Feign中使用熔断器

    Feign是自带熔断器的,但默认是关闭的.需要在配置文件中配置打开它,在配置文件增加以下代码:

    feign:
    hystrix:
    enabled: true

    在Service中增加fallback指定类

    import com.ley.springcloud.hystrix.feign.service.fallback.HelloServiceFallback;
    import org.springframework.cloud.netflix.feign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;

    @FeignClient(value = "eureka-provider", fallback = HelloServiceFallback.class, configuration = FullLogConfig.class)
    public interface HelloService {

       @GetMapping("/hello")
       String hello();
    }

    import com.ley.springcloud.hystrix.feign.service.HelloService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;

    //Feign的fallback指定类,必须注入到spring的容器中
    @Slf4j
    @Component
    public class HelloServiceFallback implements HelloService {

       @Override
       public String hello() {
           log.info("service {},method {},服务降级逻辑", HelloService.class.getName()
                  , "hello");
           return "request error";
      }
    }

    测试熔断器

    关闭服务提供者,再次请求http://localhost:9001/api/hystrix/feign/hello浏览器显示

    request error
  • 相关阅读:
    iOS 单例(Singleton)总结 和第三库引用单例
    iOS OpenURL用法简介
    CGContextRef学习笔记
    iOS 绘图(虚线、椭圆)
    iPhone4s 7.0.3-4 TableView 数据越界 解决方案
    Android Media应用开发
    RTMP & HLS
    Debug tool 学习笔记
    video codec 学习笔记
    matplotlib和numpy 学习笔记
  • 原文地址:https://www.cnblogs.com/liuenyuan1996/p/10291925.html
Copyright © 2020-2023  润新知