1. 隔离(线程池隔离和信号量隔离): 限制调用分布式服务的资源使用, 某一个调用的服务出现问题不会影响其他服务调用.
2. 降级: 超时降级, 资源不足时 (线程或信号量) 降级, 降级后可以配合降级接口返回托底数据.
3. 熔断: 当失败率达到阀值自动触发降级(如因网络故障 / 超时造成的失败率高), 熔断器触发的快速失败会进行快速恢复.
4. 缓存: 提供了请求缓存, 请求合并实现.
二, 环境准备:
最终目录结构:
本系列文章, 都是层层递进的, 本章内容在前面搭建好的项目框架上进行开发讲解, 对搭建 springcloud 的多模块子项目框架不清楚的同学可以参考: 一起来学 Spring Cloud | 第一章 : 如何搭建一个多模块的 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. 运行项目
1 先启动 springcloud-eureka-server 模块, 开启 eureka 注册中心
2 启动 springcloud-eureka-client 模块, 开启提供远程服务功能, 并且提供接口能力 /hello
3 启动 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 有许多配置项可以使用, 我们可以根据相应业务配进行合理配置
来源: https://www.cnblogs.com/haly/p/10905469.html