一.简介
微服务架构中如果服务提供者不可用将会导致服务消费者也不可用,这种基础服务故障导致级联故障称为雪崩效应
。通常微服务架构系统都有多个服务层,雪崩效应更显著。
容错处理机制:
1.网络请求设置超时:通常一次远程调用对应一个线程,长时间得不到响应将导致系统资源长时间得不到释放
2.使用断路器模式:正常情况下断路器处于关闭状态,可以正常请求服务;当失败率到一定阈值时断路器会打开,不会代理请求需要的服务;断路器打开一段时间后会进入”半开“状态,允许一个请求访问服务,如果请求成功则关闭断路器,否则继续保存打开状态。
Hystrix:
Hystrix是netflix开源的防止服务级联失败的容错库。Hystrix会实时监控服务调用情况(失败、超时等),当服务调用失败到达一定阈值时断路器会自动打开。请求失败、超时、或断路器打开时会执行回退逻辑。
二.Hystrix容错方式
(一).@HystrixCommand容错
1.consumer-user引入Hystrix依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.启动类增加@EnableCircuitBreaker注解开启熔断处理机制
@SpringBootApplication
@EnableFeignClients({
"com.vincent.consumer.feign"})
@EnableCircuitBreaker
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
}
3.@HystrixCommand修饰方法,使其具备容错能力
package com.vincent.consumer.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.vincent.consumer.feign.IUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class TestContr