Java之 Spring Cloud 微服务搭建 Hystrix (第二个阶段)SpringBoot项目实现商品服务器端是调用

Posted 蓝盒子itbluebox

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java之 Spring Cloud 微服务搭建 Hystrix (第二个阶段)SpringBoot项目实现商品服务器端是调用相关的知识,希望对你有一定的参考价值。

一、服务熔断Hystrix入门

1、 服务容错的核心知识

(1)雪崩效应

在微服务架构中,一个请求需要调用多个服务是非常常见的。

如客户端访问A服务,而A服务需要调用B服务,B服务需要调用C服务,由于网络原因或者自身的原因,如果B服务或者C服务不能及时响应,A服务将处于阻塞状态,直到B服务C服务响应。

此时若有大量的请求涌入,容器的线程资源会被消耗完毕,导致服务瘫痪。

服务与服务之间的依赖性,故障会传播,造成连锁反应,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。


雪崩是系统中的蝴蝶效应导致其发生的原因多种多样,有不合理的容量设计,或者是高并发下某一个方法响应变慢,亦或是某台机器的资源耗尽。

从源头上我们无法完全杜绝雪崩源头的发生,但是雪崩的根本原因来源于服务之间的强依赖,所以我们可以提前评估,做好熔断,隔离,限流。

(2)服务隔离

顾名思义,它是指将系统按照一定的原则划分为若干个服务模块,各个模块之间相对独立,无强依赖。

当有故障发生时,能将问题和影响隔离在某个模块内部,而不扩散风险,不波及其它模块,不影响整体的系统服务。

(3)熔断降级

熔断这一概念来源于电子工程中的断路器(Circuit Breaker)。
在互联网系统中,当下游服务因访问压力过大而响应变慢或失败,上游服务为了保护系统整体的可用性,可以暂时切断对下游服务的调用。
这种牺牲局部,保全整体的措施就叫做熔断。

所谓降级,就是当某个服务熔断之后,服务器将不再被调用,此时客户端可以自己准备一个本地的fallback回调,返回一个缺省值。 也可以理解为兜底。切断以后资源被释放,其他的服务性能提升

(4)服务限流

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

2、 Hystrix介绍


Hystrix是由Netflix开源的一个延迟和容错库,用于隔离访问远程系统、服务或者第三方库,防止级联失败,从而提升系统的可用性与容错性。Hystrix主要通过以下几点实现延迟和容错。

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

3、 Rest实现服务熔断

(1)order_service_rest工程中添加Hystrix的相关依赖

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

(2)开启熔断

在RestOrderApplication当中添加 @EnableCircuitBreaker 注解开启对熔断器的支持。
可以看到,我们类上的注解越来越多,在微服务中,经常会引入上面的三个注解,于是Spring就提供了
一个组合注解:@SpringCloudApplication

package cn.itbluebox.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
//@SpringBootApplication
//激活Hystrix
//@EnableCircuitBreaker
@EntityScan("cn.itbluebox.order.entity")
@SpringCloudApplication
public class RestOrderApplication 

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

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

(3)配置熔断降级业务逻辑在OrderController当中

@RestController
@RequestMapping("/order")
/**
 * @DefaultProperties : 指定此接口中公共的熔断设置
 *      如果过在@DefaultProperties指定了公共的降级方法
 *      在@HystrixCommand不需要单独指定了
 */
//@DefaultProperties(defaultFallback = "defaultFallBack")
public class OrderController 
	@Autowired
	private RestTemplate restTemplate;
	/**
	 * 使用注解配置熔断保护
	 *     fallbackmethod : 配置熔断之后的降级方法
	 */
	@HystrixCommand(fallbackMethod = "orderFallBack")
	@RequestMapping(value = "/buy/id",method = RequestMethod.GET)
	public Product findById(@PathVariable Long id) 
		if(id != 1) 
			throw  new  RuntimeException("服务器异常");
		
		return restTemplate.getForObject("http://service-product/product/1",Product.class);
	
	/**
	 * 降级方法
	 *  和需要收到保护的方法的返回值一致
	 *  方法参数一致
	 */
	public Product orderFallBack(Long id) 
		Product product = new Product();
		product.setProductName("触发降级方法");
		return product;
	

有代码可知,为 findById方法编写一个回退方法orderFallBack,
该方法与 findById方法具有相同的参数与返回值类型,该方法返回一个默认的错误信息。

findById方法上,使用注解@HystrixCommandfallbackMethod属性,指定熔断触发的降级方法是 orderFallBack

因为熔断的降级逻辑方法必须跟正常逻辑方法保证:
相同的参数列表和返回值声明。在 findById方法上 HystrixCommand(fallbackMethod = "orderFallBack") 用来声明一个降级逻辑的方法

(4)启动测试


访问:http://localhost:9004/order/buy/1

(5)超时设置

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

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000  #默认的连接的超时时间是1秒,若1秒没有返回数据,会自动触发降级逻辑

启动测试

http://localhost:9004/order/buy/1

这时我们将product_service停止

再次访问:http://localhost:9004/order/buy/1
运行成功:触发降级方法

(6)统一降级配置

在OrderController当中指定统一的降级方法

package cn.itbluebox.order.controller;

import cn.itbluebox.order.entity.Product;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RestController
@RequestMapping("/order")
/**
 * @DefaultProperties : 指定此接口中公共的熔断设置
 *      如果过在@DefaultProperties指定了公共的降级方法
 *      在@HystrixCommand不需要单独指定了
 */
@DefaultProperties(defaultFallback = "defaultFallBack")
public class OrderController 
	@Autowired
	private RestTemplate restTemplate;
	/**
	 * 使用注解配置熔断保护
	 *     fallbackmethod : 配置熔断之后的降级方法
	 */
	@HystrixCommand
	@RequestMapping(value = "/buy/id",method = RequestMethod.GET)
	public Product findById(@PathVariable Long id) 
		if(id != 1) 
			throw  new  RuntimeException("服务器异常");
		
		return restTemplate.getForObject("http://service-product/product/1",Product.class);
	
	/*
	指定统一的降级方法
		参数:没有参数
	 */
	public Product defaultFallBack()
		Product product = new Product();
		product.setProductName("触发统一的降级方法");
		return product;
	
	/**
	 * 降级方法
	 *  和需要收到保护的方法的返回值一致
	 *  方法参数一致
	 */
	public Product orderFallBack(Long id) 
		Product product = new Product();
		product.setProductName("触发降级方法");
		return product;
	


启动运行测试

访问http://localhost:9004/order/buy/1

4、Feign实现服务熔断

SpringCloud Fegin默认已为Feign整合了hystrix,所以添加Feign依赖后就不用在添加hystrix,那么怎么才能让Feign的熔断机制生效呢,只要按以下步骤开发:

(1)修改order_service_feign当中的application.yml在Fegin中开启hystrix

在Feign中已经内置了hystrix,但是默认是关闭的需要在工程的 application.yml 中开启对hystrix的支持

  hystrix: #在feign中开启hystrix熔断
    enabled: true

(2)配置FeignClient接口的实现类

基于Feign实现熔断降级,那么降级方法需要配置到FeignClient接口的实现类中
在order_service_feign当中创建ProductFeignClientCallBack

package cn.itbluebox.order.feign;
import cn.itbluebox.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;
	

(3)启动运行测试


访问:http://localhost:9003/order/buy/1

5、Hystrix 的超时时间


#默认的连接的超时时间是1秒,若1秒没有返回数据,会自动触发降级逻辑

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000  #默认的连接的超时时间是1秒,若1秒没有返回数据,会自动触发降级逻辑,这里设置的是3秒

二、服务熔断Hystrix高级

我们知道,当请求失败,被拒绝,超时的时候,都会进入到降级方法中。但进入降级方法并不意味着断路器已经被打开。那么如何才能了解断路器中的状态呢?

1、Hystrix的监控平台

除了实现容错功能,Hystrix还提供了近乎实时的监控HystrixCommandHystrixObservableCommand在执行时,会生成执行结果和运行指标。

比如每秒的请求数量,成功数量等。

这些状态会暴露在Actuator提供的/health端点中。
只需为项目添加 spring-boot-actuator 依赖,重启项目,
即可看到实时的监控数据。

1)导入依赖

		<!--引入Hystrix的监控信息 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>

2)添加EnableCircuitBreaker注解(激活Hystrix)

package cn.itbluebox.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EntityScan("cn.itbluebox.order.entity")
//激活Feign
@EnableFeignClients
//激活Hystrix
@EnableCircuitBreaker
public class FeignOrderApplication 
	public static void main(String[] args) 
		SpringApplication.run(FeignOrderApplication.class,args);
	

3)设置暴露所有actuator监控的断点

management:
  endpoints:
    web:
      exposure:
        include: '*'

4)运行测试并访问


访问:http://localhost:9003/actuator/hystrix.stream


访问http://localhost:9003/order/buy/1

再次访问:http://localhost:9003/actuator/hystrix.stream

5)搭建Hystrix DashBoard监控

刚刚讨论了Hystrix的监控,但访问/hystrix.stream接口获取的都是已文字形式展示的信息。很难通过文字直观的展示系统的运行状态,所以Hystrix官方还提供了基于图形化的DashBoard(仪表板)监控平台。

Hystrix仪表板可以显示每个断路器(被@HystrixCommand注解的方法)的状态。

(1)添加EnableHystrixDashboard 注解

在启动类使用@EnableHystrixDashboard注解激活仪表盘项目

package cn.itbluebox.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EntityScan("cn.itbluebox.order.entity")
//激活Feign
@EnableFeignClients
//激活Hystrix
@EnableCircuitBreaker
//激活仪表盘项目
@EnableHystrixDashboard
public class FeignOrderApplication 
	public static void main(String[] args) 
		SpringApplication.run(FeignOrderApplication.class,args);
	

(2)运行测试


访问:http://localhost:9003/hystrix
在下列输入框当中输入:http://localhost:9003/actuator/hystrix.stream

点击:Monitor Stream


参数解释

2、断路器聚合监控Turbine

在微服务架构体系中,每个服务都需要配置Hystrix DashBoard监控。

如果每次只能查看单个实例的监控数据,就需要不断切换监控地址,这显然很不方便。要想看这个系统的Hystrix Dashboard数据就需要用到Hystrix Turbine。

Turbine是一个聚合所有Hystrix 监控数据的工具,他可以将所有相关微服务的Hystrix 监控数据聚合到一起,方便使用。引入Turbine后,整个监控系统架构如下:

(1) 搭建TurbineServer

1)创建工程 hystrix_turbine


2) 引入相关坐标

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

以上是关于Java之 Spring Cloud 微服务搭建 Hystrix (第二个阶段)SpringBoot项目实现商品服务器端是调用的主要内容,如果未能解决你的问题,请参考以下文章