1. 隔离(线程池隔离和信号量隔离):限制调用分布式服务的资源使用,某一个调用的服务出现问题不会影响其他服务调用。
2. 降级:超时降级、资源不足时(线程或信号量)降级,降级后可以配合降级接口返回托底数据。
3. 熔断:当失败率达到阀值自动触发降级(如因网络故障/超时造成的失败率高),熔断器触发的快速失败会进行快速恢复。
4. 缓存:提供了请求缓存、请求合并实现。
如果想要了解更多的Hystrix的底层及实现原理,可以参考相关文章学习,本系列主要讲解如何快速在工作中使用Hystrix。
二、环境准备:
最终目录结构:
本系列文章,都是层层递进的,本章内容在前面搭建好的项目框架上进行开发讲解,对搭建springcloud的多模块子项目框架不清楚的同学可以参考:
工作中,我们基本上都是使用feign进行服务调用的,所以本章只讲解Feign中使用断路器,对上一章feign工程搭建有兴趣的可以参考:一起来学Spring Cloud | 第四章:服务消费者 ( Feign )
三、Feign中使用断路器:
1. 在上章的springcloud-feign-client工程的application.properties配置文件中,加入配置:feign.hystrix.enabled=true
server.port=9600
spring.application.name=springcloud-feign-client
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
feign.hystrix.enabled=true
2. 在上章的springcloud-feign-client工程中,新增一个FeignRemoteService类的实现类,命名为:HystrixFeignRemoteCallBack,做为出现接口异常时的回调方法
package com.haly.romote.hystrix;
import org.springframework.stereotype.Component;
import com.haly.romote.FeignRemoteService;
@Component
public class HystrixFeignRemoteCallBack implements FeignRemoteService{
@Override
public String hello(String name) {
// TODO Auto-generated method stub
return name + ",Due error,enter Hystrix";
}
}
3. 在上章的springcloud-feign-client工程中,新增一个FeignRemoteService类中加入回调实现类的注解配置
package com.haly.romote;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.haly.romote.hystrix.HystrixFeignRemoteCallBack;
@FeignClient(value = "springcloud-eureka-client",fallback = HystrixFeignRemoteCallBack.class)
public interface FeignRemoteService {
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(@RequestParam(value = "name") String name);
}
4. 运行项目
① 先启动springcloud-eureka-server模块,开启eureka注册中心
② 启动springcloud-eureka-client模块,开启提供远程服务功能,并且提供接口能力 /hello
③ 启动springcloud-feign-client模块,开启消费模块,用来调用springcloud-eureka-client模块中的/hello接口
Eureka上的注册信息,如下图:
打开浏览器,输入网址:http://localhost:9600/getHello?name=young码农,运行结果如下:
我们模仿生产环境,服务提供者宕机(或者返回超时),这里我们手动停掉springcloud-eureka-client服务
输入网址:http://localhost:9600/getHello?name=young码农
本章我们只是在回调接口中,返回一个字符串,工作中,有些场景会做一些业务逻辑处理(比如调用短信发送接口,出现异常会在记录一条异常日志,后面来处理这些异常)。
工作中我们会遇到很多特殊场景,特别在访问量过大,业务较复杂的时候,会出现一些奇奇怪怪的问题,所以Feign,Hystrix有许多配置项可以使用,我们可以根据相应业务配进行合理配置