服務雪崩效應
當請求的服務中出現無法通路、異常、逾時等問題時,那麼使用者的請求将會被阻塞。如果多個使用者的請求中,都存在無法通路的服務,那麼他們都将陷入阻塞的狀态中。
在微服務架構中,根據業務來拆分成一個個的服務,服務與服務之間可以互相調用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign來調用。為了保證其高可用,單個服務通常會叢集部署。由于網絡原因或者自身的原因,服務并不能保證100%可用,如果單個服務出現問題,調用這個服務就會出現線程阻塞,此時若有大量的請求湧入,Servlet容器的線程資源會被消耗完畢,導緻服務癱瘓。服務與服務之間的依賴性,故障會傳播,會對整個微服務系統造成災難性的嚴重後果,這就是服務故障的“雪崩”效應。
Hystrix的引入,可以通過服務熔斷和服務降級來解決這個問題。
解決服務雪崩效應原理:
1)服務降級
在高并發情況下,防止使用者一直等待,使用服務降級方式(傳回一個友好的提示直接給用戶端,不會去處理請求,調用fallback本地方法),目的是為了使用者體驗
比如秒殺–目前請求人數過多,請稍後重試。(在tomcat中沒有線程進行處理用戶端請求的時候,不應該讓使用者一直轉圈等待。)
2)服務熔斷
例如保險絲,服務熔斷的目的是為了保護服務,在高并發情況下,如果請求達到了一定的極限(可以自己設定門檻值),如果流量超出了設定的門檻值,會自動開啟保護服務功能,使用服務降級方式傳回一個友好的提示。
熔斷機制和服務降級一起使用。
預設門檻值為10個
3)服務隔離
采用線程池隔離,每個服務接口都有自己獨立的線程池,每個線程池互不影響;
缺點:CPU占用率非常高。
服務熔斷服務降級
在一個分布式系統裡,許多依賴不可避免的會調用失敗,比如逾時、異常等,如何能夠保證在一個依賴出問題的情況下,不會導緻整體服務失敗,這個就是Hystrix需要做的事情。Hystrix提供了熔斷、隔離、Fallback、cache、監控等功能,能夠在一個、或多個依賴同時出現問題時保證系統依然可用。
Hystrix服務熔斷服務降級@HystrixCommand fallbackMethod
熔斷機制是應對雪崩效應的一種微服務鍊路保護機制。
當某個服務不可用或者響應時間逾時,會進行服務降級,進而熔斷該節點的服務調用,快速傳回自定義的錯誤影響頁面資訊。
我們寫一個新的帶服務熔斷的服務提供者項目 microservice-student-provider-hystrix-1004
pom依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lx</groupId>
<artifactId>springcloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-provider-hystrix-1004</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.lx</groupId>
<artifactId>microservice-common</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!-- 修改後立即生效,熱部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>com.lx</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--添加注冊中心Eureka相關配置-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- actuator監控引入 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--Hystrix相關依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml修改下端口和執行個體名稱
server:
port: 1004
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/tb_0523?useUnicode=true&characterEncoding=utf8
username: root
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application:
name: microservice-student
eureka:
instance:
hostname: localhost
appname: microservice-student
instance-id: microservice-student:1004
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.lx.com:2001/eureka/,http://eureka2002.lx.com:2002/eureka/,http://eureka2003.lx.com:2003/eureka/
info:
groupId: com.lx.springcloud
artifactId: microservice-student-provider-hystrix-1004
version: 1.0-SNAPSHOT
userName: http://lx.com
phone: 123456
啟動類StudentProviderHystrixApplication_1004加下注解支援
package com.lx.microservicestudentproviderhystrix1004;
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.eureka.EnableEurekaClient;
@EnableCircuitBreaker
@EntityScan("com.lx.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderHystrix1004Application {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentProviderHystrix1004Application.class, args);
}
}
服務提供者1004中controller新增
package com.lx.microservicestudentproviderhystrix1004.controller;
import com.lx.microservicecommon.entity.Student;
import com.lx.microservicestudentproviderhystrix1004.service.StudentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/student")
public class StudentProviderController {
@Autowired
private StudentService studentService;
@Value("${server.port}")
private String port;
@PostMapping(value="/save")
public boolean save(Student student){
try{
studentService.save(student);
return true;
}catch(Exception e){
return false;
}
}
@GetMapping(value="/list")
public List<Student> list(){
return studentService.list();
}
@GetMapping(value="/get/{id}")
public Student get(@PathVariable("id") Integer id){
return studentService.findById(id);
}
@GetMapping(value="/delete/{id}")
public boolean delete(@PathVariable("id") Integer id){
try{
studentService.delete(id);
return true;
}catch(Exception e){
return false;
}
}
@RequestMapping("/ribbon")
public String ribbon(){
return "工号【"+port+"】正在為您服務";
}
/**
* 測試Hystrix服務降級
* @return
* @throws InterruptedException
*/
@ResponseBody
@GetMapping(value="/hystrix")
@HystrixCommand(fallbackMethod="hystrixFallback")
public Map<String,Object> hystrix() throws InterruptedException{
Thread.sleep(1000);
Map<String,Object> map=new HashMap<String,Object>();
map.put("code", 200);
map.put("info","工号【"+port+"】正在為您服務");
return map;
}
public Map<String,Object> hystrixFallback() throws InterruptedException{
Map<String,Object> map=new HashMap<String,Object>();
map.put("code", 500);
map.put("info", "系統【"+port+"】繁忙,稍後重試");
return map;
}
}
然後我們在消費者microservice-student-consumer-80的controller加上方法
/**
* 測試Hystrix服務降級
* @return
*/
@GetMapping(value="/hystrix")
@ResponseBody
public Map<String,Object> hystrix(){
return restTemplate.getForObject(SERVER_IP_PORT+"/student/hystrix/", Map.class);
}
然後我們來測試下
先啟動三個eureka,再啟動帶hystrix的provider,最後啟動普通的consumer;
浏覽器:http://localhost/student/hystrix

因為 Hystrix預設1算逾時,所有 sleep了2秒 是以進入自定義fallback方法,防止服務雪崩
我們這裡改sleep修改成1000毫秒
Hystrix預設逾時時間設定
Hystrix預設逾時時間是1秒,我們可以通過hystrix源碼看到,
找到 hystrix-core.jar com.netflix.hystrix包下的HystrixCommandProperties類
default_executionTimeoutInMilliseconds屬性局勢預設的逾時時間
自定義設定hystrix的預設時間的話;
application.yml配置檔案加上
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
Hystrix服務監控Dashboard
Hystrix服務監控Dashboard儀表盤
Hystrix提供了 準實時的服務調用監控項目Dashboard,能夠實時記錄通過Hystrix發起的請求執行情況,
可以通過圖表的形式展現給使用者看。
我們建立項目:microservice-student-consumer-hystrix-dashboard-90
加依賴:
<!--Hystrix服務監控Dashboard依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
application.yml配置
server:
port: 90
context-path: /
在啟動類:StudentConsumerDashBoardApplication_90加注解:@EnableHystrixDashboard
package com.lx.microservicestudentconsumerhystrixdashboard90;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableHystrixDashboard
public class MicroserviceStudentConsumerHystrixDashboard90Application {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentConsumerHystrixDashboard90Application.class, args);
}
}
我們啟動這個項目;
然後浏覽器輸入:http://localhost:90/hystrix
然後我們輸入我們要監控的項目和方法路徑
http://localhost:1004/student/hystrix