微服务框架(Spring Cloud,Dubbo)中将业务划分为许多微业务模块进行管理,这样会导致微服务间相互调用,彼此依赖,如果某一个环节的微服务出现问题,整个调用链条都会出现问题,会阻塞所有调用此服务的线程。Netflix为解决此问题根据断路器模式设计了Hystrix库,"断路器"是电气设备中的一种开关装置,当某个服务出现故障后,通过断路器的故障监控,向调用线程返回一个符号预期可处理的备选响应(Fallback),从而避免线程长时间等待或者抛出异常,这样保证了服务调用线程不会被长时间被占用,从而避免故障在微服务系统中的蔓延,乃至雪崩。
假设:一个服务依赖30个微服务,每个微服务99.99%可用。
99.99%的30次方 ≈ 99.7%
0.3% 意味着一千次请求 会有 3次失败
按照时间换算大约每月有2个小时时间服务出现问题。
如果服务依赖数量继续增加,服务不稳定导致的后果更加严重。
Hystrix如何进行熔断与调用隔离
Hystrix使用命令模式HystrixCommand(Command)包装依赖调用逻辑,每个命令在单独线程中/信号授权下执行。
可配置依赖调用超时时间,超时时间一般设为比99.5%平均时间略高即可.当调用超时时,直接返回或执行fallback逻辑。
为每个依赖提供一个小的线程池(或信号),如果线程池已满调用将被立即拒绝,默认不采用排队.加速失败判定时间。
依赖调用结果分:成功,失败(抛出异常),超时,线程拒绝,短路。 请求失败(异常,拒绝,超时,短路)时执行fallback(降级)逻辑。
提供熔断器组件,可以自动运行或手动调用,停止当前依赖一段时间(10秒),熔断器默认错误率阈值为50%,超过将自动运行。
提供近实时依赖的统计和监控。
Hystrix容错机制
设计Eureka注册中心
POM.xml
<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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>eureka-server</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>eureka-server Maven Webapp</name>
<url>http://maven.apache.org</url>
<!--
SpringCloud是基于SpringBoot框架的,必须引入SpringBoot的依赖
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!--
Spring Cloud的命名没有按照版本方式管理,是采用命名方式,
版本名称采用伦敦地铁站的名称命名,根据字母表的顺序对应版本时间顺序,
比如最早的Release版本号为Angel,第二个Release版本为Brixton
-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--
Eureka 服务依赖
-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<!--
SpringBoot集成Spring Security
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<!--
根据SpringCloud约定打成可以独立执行Jar包,使用Maven命令
mvn package spring-boot:repackage
-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=8110
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:8110/eureka/
security.user.name=chenqx
security.user.password=123
EureKaServer启动类
package com.test.eureka_server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EureKaServer
{
public static void main( String[] args )
{
SpringApplication.run(EureKaServer.class, args);
}
}
设计微服务提供者
POM.xml
<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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>eureka-service-order</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>eureka-service-order Maven Webapp</name>
<url>http://maven.apache.org</url>
<!--
SpringCloud是基于SpringBoot框架的,必须引入SpringBoot的依赖
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<!--
Spring Cloud的命名没有按照版本方式管理,是采用命名方式,
版本名称采用伦敦地铁站的名称命名,根据字母表的顺序对应版本时间顺序,
比如最早的Release版本号为Angel,第二个Release版本为Brixton
-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!--
根据SpringCloud约定打成可以独立执行Jar包,使用Maven命令
mvn package spring-boot:repackage
-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=9100
spring.application.name=service-order
eureka.client.service-url.defaultZone=http://chenqx:123@localhost:8110/eureka
eureka.client.register-with-eureka=true
eureka.client.registry-fetch-interval-seconds=10
eureka.client.fetch-registry=true
实体类
package com.test.eureka_service_order;
import java.io.Serializable;
import java.sql.Date;
public class OrderInfo implements Serializable {
private static final long serialVersionUID = -7233238826463139634L;
private Long id;
private String name;
private String prdtName;
private Integer count;
private Integer amount;
private Date createDt = new Date(System.currentTimeMillis());
private String userId = null;
public OrderInfo() {
}
public OrderInfo(String name,String prdtName,Integer count,Integer amount,Date createDt,String userId) {
this.name = name;
this.prdtName = prdtName;
this.count = count;
this.amount = amount;
this.createDt = createDt;
this.userId = userId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrdtName() {
return prdtName;
}
public void setPrdtName(String prdtName) {
this.prdtName = prdtName;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
",prdtName=" + prdtName +
",count=" + count +
",amount=" + amount +
'}';
}
}
服务类
package com.test.eureka_service_order;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Date;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderServiceApiImpl{
@RequestMapping(value = "/hello1", method = RequestMethod.GET)
public String hello(@RequestParam("name") String name) {
System.out.println("name="+name);
return "hello " + name;
}
@RequestMapping(value = "/hello2", method = RequestMethod.GET)
public OrderInfo hello(@RequestHeader("name") String name,
@RequestHeader("prdtName") String prdtName,
@RequestHeader("count") Integer count,
@RequestHeader("amount") Integer amount,
@RequestHeader("createDt") Date createDt,
@RequestHeader("userId") String userId) {
try {
name= URLDecoder.decode(name,"UTF-8");
prdtName= URLDecoder.decode(prdtName,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new OrderInfo(name, prdtName,count,amount,createDt,userId);
}
@RequestMapping(value = "/hello3", method = RequestMethod.GET)
public String hello(@RequestBody OrderInfo order) {
if (order == null) {
return "未知";
}
return order.toString();
}
}
启动类
package com.test.eureka_service_order;
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;
@EnableDiscoveryClient
@SpringBootApplication
public class OrderServer
{
public static void main( String[] args )
{
SpringApplication.run(OrderServer.class, args);
}
}
设计服务消费者
POM.xml
<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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--
SpringCloud是基于SpringBoot框架的,必须引入SpringBoot的依赖
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<groupId>com.test</groupId>
<artifactId>eureka-service-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>eureka-service-web</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<!--
Spring Cloud的命名没有按照版本方式管理,是采用命名方式,
版本名称采用伦敦地铁站的名称命名,根据字母表的顺序对应版本时间顺序,
比如最早的Release版本号为Angel,第二个Release版本为Brixton
-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!--
根据SpringCloud约定打成可以独立执行Jar包,使用Maven命令
mvn package spring-boot:repackage
-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
实体类与服务提供者中的相同
定义Feign接口
package com.test.eureka_service_web;
import java.sql.Date;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "service-order",fallback=OrderFallBackImpl.class)
public interface OrderBackgroundService{
@RequestMapping(value = "/hello1", method = RequestMethod.GET)
public String hello(@RequestParam("name") String name);
@RequestMapping(value = "/hello2", method = RequestMethod.GET)
public OrderInfo hello(@RequestHeader("name") String name,
@RequestHeader("prdtName") String prdtName,
@RequestHeader("count") Integer count,
@RequestHeader("amount") Integer amount,
@RequestHeader("createDt") Date createDt,
@RequestHeader("userId") String userId);
@RequestMapping(value = "/hello3", method = RequestMethod.GET)
public String hello(@RequestBody OrderInfo order);
}
设计OrderFallBackImpl
package com.test.eureka_service_web;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Date;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Component
public class OrderFallBackImpl implements OrderBackgroundService{
public String hello(@RequestParam("name") String name) {
return "返回Fallback.hello";
}
public OrderInfo hello(@RequestHeader("name") String name,
@RequestHeader("prdtName") String prdtName,
@RequestHeader("count") Integer count,
@RequestHeader("amount") Integer amount,
@RequestHeader("createDt") Date createDt,
@RequestHeader("userId") String userId) {
name= "Fallback Name";
prdtName= "Fallback PrdtName";
return new OrderInfo(name, prdtName,count,amount,createDt,userId);
}
public String hello(@RequestBody OrderInfo order) {
return "返回Fallback.hello3";
}
}
消费者Controller
package com.gf.eureka_order_client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
@Autowired
private OrderBackgroundService service;
@RequestMapping("/hello1")
public String hello1(){
return service.hello("Java");
}
}
启动类
package com.test.eureka_service_web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import feign.Logger;
@EnableCircuitBreaker
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class OrderClient
{
@Bean
Logger.Level feginLoggerLevel(){
return Logger.Level.FULL;
}
public static void main(String[] args) {
SpringApplication.run(OrderClient.class, args);
}
}
application.properties
server.port=8887
spring.application.name=order-service-web
eureka.instance.hostname=localhost
eureka.instance.server.port=8110
eureka.client.serviceUrl.defaultZone=http://chenqx:123@${eureka.instance.hostname}:${eureka.instance.server.port}/eureka/
feign.hystrix.enabled=true
测试效果
分别启动EurekaServer注册中心,服务和消费者
停止SERVICE-ORDER服务后,再次请求http://localhost:8887/hello1