2021-12-19 周天
## Hystrix介紹
Hystrix是由Netflix開源的一個延遲和容錯庫,用于隔離訪問遠程系統、服務或者第三方庫,防止級聯失敗,從而提升系統的可用性與容錯性。
### Hystrix特性
Hystrix主要通過以下幾點實現延遲和容錯。
* 包裹請求 - `@HystrixCommand`注解(命令模式)
* 跳閘機制 - 5秒內20次失敗,一段時間內會停止訪問服務
* 資源隔離 - 給每個服務提供小型線程池,線程池滿立即拒絕請求
* 監控
* 回退機制 - 開發人員可提供默認回退邏輯
* 自我修復 - 一段時間內,會嘗試調用一次服務,請求成功則關閉斷路器
## Hystrix 集成
### 添加依賴
``` xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
```
### 開啟斷路器
在啟動類上增加`@EnableHystrix`注解或者`@EnableCircuitBreaker`注解。
### 直接使用`@HystrixCommand`
``` java
@FeignClient(name = "mic-card",path = "/card/admin")
public interface CardApi {
@PostMapping("/count/home")
@HystrixCommand
ResultObject<CountVo> getHome();
}
```
### 結合Feign使用
Feign默認是不啟用Hystrix的,添加如下配置啟用。
``` yml
feign:
hystrix:
enabled: true
```
``` java
/**
* @Description card api服務
* @Date 2021-12-04 10:12
* @Created by mango
*/
@FeignClient(name = "mic-card",path = "/card/admin",
configuration = {FeignConfiguration.class},
fallback = CardApiFallback.class)
public interface CardApi {
@GetMapping("/card/rand")
ResultObject<CardVo> getRand();
@PostMapping("/count/home")
ResultObject<CountVo> getHome();
}
## 回退機制,自定義實現回退邏輯
@Component
@Slf4j
class CardApiFallback implements CardApi {
@Autowired
private ResultUtil resultUtil;
@Override
public ResultObject<CardVo> getRand() {
log.info("enter card api fallback");
CardVo cardVo = new CardVo();
cardVo.setName("enter fallback");
cardVo.setIsOpen("1");
cardVo.setCreateTime(DateUtil.now());
return resultUtil.success2obj(cardVo,"success");
}
@Override
public ResultObject<CountVo> getHome() {
log.info("enter card api get home fallback");
CountVo countVo = new CountVo();
countVo.setCardCount(1);
countVo.setFileCount(1);
countVo.setPointCount(1);
return resultUtil.success2obj(countVo,"success");
}
}
```
## 配置相關
### 全局啟用
~~~
feign.hystrix.enabled: true
~~~
#### 全局禁用
~~~
feign.hystrix.enabled: false
~~~
### 局部啟用
~~~
public class FeignEnableHystrixConfiguration {
@Bean
@Scope("prototype")
public HystrixFeign.Builder feignBuilder() {
return HystrixFeign.builder();
}
}
~~~
~~~
@FeignClient(name = "mic-card",path = "/card/admin",
configuration = {FeignEnableHystrixConfiguration.class},
fallback = CardApiFallback.class)
~~~
## 局部禁用
~~~
public class FeignDisableHystrixConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}
~~~
## @HystrixCommand注解源碼
``` java
/**
* This annotation used to specify some methods which should be processes as hystrix commands.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface HystrixCommand {
/**
* The command group key is used for grouping together commands such as for reporting,
* alerting, dashboards or team/library ownership.
* <p/>
* default => the runtime class name of annotated method
*
* @return group key
*/
String groupKey() default "";
/**
* Hystrix command key.
* <p/>
* default => the name of annotated method. for example:
* <code>
* ...
* @HystrixCommand
* public User getUserById(...)
* ...
* the command name will be: 'getUserById'
* </code>
*
* @return command key
*/
String commandKey() default "";
/**
* The thread-pool key is used to represent a
* HystrixThreadPool for monitoring, metrics publishing, caching and other such uses.
*
* @return thread pool key
*/
String threadPoolKey() default "";
/**
* Specifies a method to process fallback logic.
* A fallback method should be defined in the same class where is HystrixCommand.
* Also a fallback method should have same signature to a method which was invoked as hystrix command.
* for example:
* <code>
* @HystrixCommand(fallbackMethod = "getByIdFallback")
* public String getById(String id) {...}
*
* private String getByIdFallback(String id) {...}
* </code>
* Also a fallback method can be annotated with {@link HystrixCommand}
* <p/>
* default => see {@link com.netflix.hystrix.contrib.javanica.command.GenericCommand#getFallback()}
*
* @return method name
*/
String fallbackMethod() default "";
/**
* Specifies command properties.
*
* @return command properties
*/
HystrixProperty[] commandProperties() default {};
/**
* Specifies thread pool properties.
*
* @return thread pool properties
*/
HystrixProperty[] threadPoolProperties() default {};
/**
* Defines exceptions which should be ignored.
* Optionally these can be wrapped in HystrixRuntimeException if raiseHystrixExceptions contains RUNTIME_EXCEPTION.
*
* @return exceptions to ignore
*/
Class<? extends Throwable>[] ignoreExceptions() default {};
/**
* Specifies the mode that should be used to execute hystrix observable command.
* For more information see {@link ObservableExecutionMode}.
*
* @return observable execution mode
*/
ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;
/**
* When includes RUNTIME_EXCEPTION, any exceptions that are not ignored are wrapped in HystrixRuntimeException.
*
* @return exceptions to wrap
*/
HystrixException[] raiseHystrixExceptions() default {};
/**
* Specifies default fallback method for the command. If both {@link #fallbackMethod} and {@link #defaultFallback}
* methods are specified then specific one is used.
* note: default fallback method cannot have parameters, return type should be compatible with command return type.
*
* @return the name of default fallback method
*/
String defaultFallback() default "";
}
```
## 參考資料
* https://www.itmuch.com/spring-cloud/finchley-13/
- Redis來回摩擦
- redis的數據結構SDS和DICT
- redis的持久化和事件模型
- Java
- 從何而來之Java IO
- 發布Jar包到公共Maven倉庫
- Java本地方法調用
- 面試突擊
- Linux
- Nginx
- SpringBoot
- Springboot集成Actuator和SpringbootAdminServer監控
- SpringCloud
- Spring Cloud初識
- Spring Cloud的5大核心組件
- Spring Cloud的注冊中心
- Spring Cloud注冊中心之Eureka
- Spring Cloud注冊中心之Consul
- Spring Cloud注冊中心之Nacos
- Spring Cloud的負載均衡之Ribbon
- Spring Cloud的服務調用之Feign
- Spring Cloud的熔斷器
- Spring Cloud熔斷器之Hystrix
- Spring Cloud的熔斷器監控
- Spring Cloud的網關
- Spring Cloud的網關之Zuul
- Spring Cloud的配置中心
- Spring Cloud配置中心之Config Server
- Spring Cloud Config配置刷新
- Spring Cloud的鏈路跟蹤
- Spring Cloud的鏈路監控之Sleuth
- Spring Cloud的鏈路監控之Zipkin
- Spring Cloud集成Admin Server
- Docker
- docker日常基本使用
- docker-machine的基本使用
- Kubernetes
- kubernetes初識
- kubeadm安裝k8s集群
- minikube安裝k8s集群
- k8s的命令行管理工具
- k8s的web管理工具
- k8s的相關發行版
- k3s初識及安裝
- rancher的安裝及使用
- RaspberryPi
- 運維
- 域名證書更新
- 騰訊云主機組建內網
- IDEA插件開發
- 第一個IDEA插件hello ide開發
- 千呼萬喚始出來的IDEA筆記插件mdNote
- 大剛學算法
- 待整理
- 一些概念和知識點
- 位運算
- 數據結構
- 字符串和數組
- LC242-有效的字母異位詞
- 鏈表
- LC25-K個一組翻轉鏈表
- LC83-刪除有序單鏈表重復的元素
- 棧
- LC20-有效的括號
- 隊列
- 雙端隊列
- 優先隊列
- 樹
- 二叉樹
- 二叉樹的遍歷
- 二叉樹的遞歸序
- 二叉樹的前序遍歷(遞歸)
- 二叉樹的前序遍歷(非遞歸)
- 二叉樹的中序遍歷(遞歸)
- 二叉樹的中序遍歷(非遞歸)
- 二叉樹的后序遍歷(遞歸)
- 二叉樹的后序遍歷(非遞歸)
- 二叉樹的廣度優先遍歷(BFS)
- 平衡二叉樹
- 二叉搜索樹
- 滿二叉樹
- 完全二叉樹
- 二叉樹的打印(二維數組)
- 樹的序列化和反序列化
- 前綴樹
- 堆
- Java系統堆優先隊列
- 集合數組實現堆
- 圖
- 圖的定義
- 圖的存儲方式
- 圖的Java數據結構(鄰接表)
- 圖的表達方式及對應場景創建
- 圖的遍歷
- 圖的拓撲排序
- 圖的最小生成樹之Prim算法
- 圖的最小生成樹之Kruskal算法
- 圖的最小單元路徑之Dijkstra算法
- 位圖
- Java實現位圖
- 并查集
- Java實現并查集
- 滑動窗口
- 單調棧
- 排序
- 冒泡排序BubbleSort
- 選擇排序SelectSort
- 插入排序InsertSort
- 插入排序InsertXSort
- 歸并排序MergeSort
- 快速排序QuickSort
- 快速排序優化版QuickFastSort
- 堆排序HeapSort
- 哈希Hash
- 哈希函數
- guava中的hash函數
- hutool中的hash函數
- 哈希表實現
- Java之HashMap的實現
- Java之HashSet的實現
- 一致性哈希算法
- 經典問題
- 荷蘭國旗問題
- KMP算法
- Manacher算法
- Go