Skip to content

Commit 70b94a3

Browse files
committed
desc:增加SpringCloudGateway之熔断集成篇,SpringCloudGateway之限流集成篇,SpringCloudGateway之统一鉴权篇文章
1 parent ec61ddd commit 70b94a3

File tree

4 files changed

+230
-1
lines changed

4 files changed

+230
-1
lines changed

docs/.vuepress/config.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,14 @@ module.exports = {
265265
text: 'SpringCloudGateway之熔断集成篇',
266266
link: '/md/spring/spring-cloud/SpringCloudGateway之熔断集成篇.md'
267267
},
268+
{
269+
text: 'SpringCloudGateway之限流集成篇',
270+
link: '/md/spring/spring-cloud/SpringCloudGateway之限流集成篇.md'
271+
},
272+
{
273+
text: 'SpringCloudGateway之统一鉴权篇',
274+
link: '/md/spring/spring-cloud/SpringCloudGateway之统一鉴权篇.md'
275+
}
268276
]
269277
}
270278
]
@@ -589,7 +597,9 @@ module.exports = {
589597
"SpringCloudGateway工作原理与链路图.md",
590598
"SpringCloudGateway核心之Predicate.md",
591599
"SpringCloudGateway之Filter多过程介绍.md",
592-
"SpringCloudGateway之熔断集成篇.md"
600+
"SpringCloudGateway之熔断集成篇.md",
601+
"SpringCloudGateway之限流集成篇.md",
602+
"SpringCloudGateway之统一鉴权篇.md"
593603
]
594604
}
595605
],
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,219 @@
11
# SpringCloudGateway之熔断集成篇
2+
> 熔断应用:
3+
> 金融市场中的熔断机制:在金融交易系统中,熔断机制(Circuit Breaker)是一种市场保护措施,旨在预防市场剧烈波动时可能导致的系统性风险。当某个基准指数(如股票指数或期货价格)在短时间内发生急剧上涨或下跌达到预先设定的阈值时,交易所会自动暂停交易一段时间或者限制涨跌幅度,类似于电器中的保险丝在电流过载时熔断以切断电流。例如,在美国股市中,曾经存在三级熔断机制,分别在标普500指数下跌7%、13%和20%时触发。
4+
> 分布式计算中的熔断机制: 在分布式系统或微服务架构中,熔断机制是一种容错设计模式,其目的是防止因依赖的服务出现故障而引发整个系统的雪崩效应。当一个服务调用另一个服务时,如果后者频繁失败或响应时间过长,熔断器组件(如Hystrix、Resilience4j或Alibaba Sentinel)就会“熔断”该调用链路,不再继续请求有问题的服务,而是直接返回预设的错误信息或默认值,同时给调用方提供一个快速的失败反馈,而不是长时间等待或阻塞资源。在后续的一段时间内(冷却期),即使问题服务恢复,熔断器也可能保持打开状态,仅在一段时间后尝试半开状态重新发起调用,以确认服务是否真正恢复正常。这样可以确保整个系统的稳定性,并允许其他健康的服务不受影响地继续运行。
25
6+
> Spring Cloud Gateway 本身并不自带完整的熔断机制,但在早期版本中可以通过集成 Hystrix 来实现服务熔断和降级。然而,随着Hystrix的维护状态变更,社区推荐使用如Resilience4j或Alibaba Sentinel等其他更活跃的容错库。
7+
## SpringCloudGateway集成Hystrix实现熔断
8+
### 第一步添加依赖:
9+
>在pom.xml或build.gradle文件中引入Spring Cloud Gateway与Hystrix的相关依赖。
10+
```xml
11+
<dependency>
12+
<groupId>org.springframework.cloud</groupId>
13+
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
14+
</dependency>
15+
```
16+
### 第二部添加路由配置
17+
> 在Spring Cloud Gateway配置中添加Hystrix过滤器,并定义相关的路由规则
18+
19+
```yaml
20+
spring:
21+
cloud:
22+
gateway:
23+
routes:
24+
- id: your_route_id
25+
uri: lb://your_service_id
26+
predicates:
27+
- Path=/api/** # 例如,匹配所有/api开头的路径
28+
filters:
29+
- name: Hystrix
30+
args:
31+
name: fallbackcmd
32+
fallbackUri: forward:/fallback # 当熔断发生时转发到的本地fallback处理逻辑
33+
```
34+
### 第三步添加回退提示
35+
> 创建一个Controller或Endpoint来处理当Hystrix触发熔断时的回退操作。
36+
37+
```java
38+
@RestController
39+
public class FallbackController {
40+
41+
@GetMapping("/fallback")
42+
public Mono<String> fallback() {
43+
return Mono.just("Fallback response due to service unavailable.");
44+
}
45+
}
46+
```
47+
### 第四步添加Hystrix熔断配置
48+
>确保Hystrix的全局配置已启用,并根据需要配置熔断阈值、超时时间等参数。
49+
50+
```java
51+
import com.netflix.hystrix.HystrixCommandProperties;
52+
53+
@Configuration
54+
public class HystrixConfiguration {
55+
56+
@Bean
57+
public HystrixCommandProperties.Setter hystrixCommandProperties() {
58+
return HystrixCommandProperties.Setter()
59+
.withExecutionTimeoutInMilliseconds(5000) // 设置命令执行超时时间为5秒
60+
.withCircuitBreakerEnabled(true) // 启用熔断器
61+
.withCircuitBreakerErrorThresholdPercentage(50) // 当错误率达到50%时触发熔断
62+
.withCircuitBreakerSleepWindowInMilliseconds(30000); // 熔断后的休眠窗口期为30秒
63+
}
64+
}
65+
```
66+
67+
```yaml
68+
hystrix:
69+
command:
70+
default: # 这里是全局默认配置,也可以针对特定命令键做单独配置
71+
execution:
72+
isolation:
73+
thread:
74+
timeoutInMilliseconds: 5000 # 设置命令执行超时时间为5秒
75+
circuitBreaker:
76+
enabled: true # 启用熔断器
77+
errorThresholdPercentage: 50 # 当错误率达到50%时触发熔断
78+
sleepWindowInMilliseconds: 30000 # 熔断后的休眠窗口期为30秒
79+
```
80+
### 第五步实现熔断逻辑
81+
>自定义熔断 Hystrix Gateway Filter来完成熔断逻辑的适配。
82+
83+
```java
84+
参考
85+
import com.netflix.hystrix.HystrixCommand;
86+
import com.netflix.hystrix.exception.HystrixRuntimeException;
87+
import org.springframework.cloud.gateway.filter.GatewayFilter;
88+
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
89+
import org.springframework.http.HttpStatus;
90+
import org.springframework.web.server.ServerWebExchange;
91+
import reactor.core.publisher.Mono;
92+
93+
public class HystrixGatewayFilterFactory extends AbstractGatewayFilterFactory<HystrixGatewayFilterFactory.Config> {
94+
95+
public static class Config {
96+
// 可配置属性,如命令名称、组键等
97+
private String commandKey;
98+
// 其他可能的配置项...
99+
100+
// 构造函数和getters/setters省略...
101+
}
102+
103+
@Override
104+
public GatewayFilter apply(Config config) {
105+
return (exchange, chain) -> {
106+
// 创建Hystrix Command,封装请求处理逻辑
107+
HystrixCommand<String> command = new HystrixCommand<String>(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(config.getCommandKey()))) {
108+
@Override
109+
protected String run() throws Exception {
110+
// 执行原始请求并获取响应
111+
return chain.filter(exchange).block();
112+
}
113+
114+
// 自定义fallback逻辑
115+
@Override
116+
```
117+
118+
## SpringCloudGateway集成Sentinel实现熔断
119+
### 第一步配置依赖
120+
121+
```xml
122+
<dependency>
123+
<groupId>com.alibaba.cloud</groupId>
124+
<artifactId>spring-cloud-starter-alibaba-sentinel-gateway</artifactId>
125+
<version>{latest_version}</version>
126+
</dependency>
127+
128+
```
129+
#### yaml配置
130+
131+
```yaml
132+
implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-sentinel-gateway:{latest_version}'
133+
```
134+
135+
### 第二步配置拦截器
136+
137+
```yaml
138+
spring:
139+
cloud:
140+
gateway:
141+
routes:
142+
- id: your_route_id
143+
uri: lb://your_service_id
144+
predicates:
145+
- Path=/your-api-path/**
146+
filters:
147+
- name: SentinelGatewayFilter
148+
args:
149+
resource: your_api_resource_name
150+
limitApp: default # 可选,限制调用来源应用,默认不限制
151+
fallbackUri: forward:/fallback # 可选,设置降级处理逻辑路径
152+
```
153+
### 第三步启动sentinel服务
154+
![202403141432485820.png](http://124.222.54.192:4000/public/upload/2024/03/14/202403141432485820.png)
155+
156+
157+
#### 通过 Docker 镜像快速部署 Sentinel 控制台
158+
>拉取 Sentinel 控制台镜像: 在终端中运行以下命令从 Docker Hub 拉取最新的 Sentinel 控制台镜像:
159+
160+
```powershell
161+
docker pull bladex/sentinel-dashboard
162+
```
163+
164+
>运行 Sentinel 控制台容器: 使用以下命令创建并启动一个 Docker 容器,其中 -p 参数用于映射宿主机端口到容器内部的 Sentinel 控制台端口(默认为 8080),--name 参数用于指定容器名称,-d 参数表示在后台运行。
165+
166+
```powershell
167+
docker run -d --name sentinel-dashboard -p 8080:8080 bladex/sentinel-dashboard
168+
```
169+
170+
>访问 Sentinel 控制台: Sentinel 控制台服务启动后,可以通过浏览器访问 http://localhost:8080 来登录控制台。默认用户名和密码都是 sentinel。
171+
172+
#### 手动下载编译后的 jar 包运行
173+
>下载 Sentinel 控制台 jar 包: 访问 [Sentinel GitHub Release](https://github.com/alibaba/Sentinel/releases) 页面 下载最新版本的 sentinel-dashboard.jar 文件。
174+
>运行 Sentinel 控制台: 在下载目录下,使用 Java 运行该 jar 包,并指定端口号(例如 8080)
175+
176+
```powershell
177+
java -jar sentinel-dashboard.jar --server.port=8080
178+
```
179+
180+
>访问 Sentinel 控制台: 同样地, Sentinel 控制台服务启动后,可以在浏览器中输入 http://localhost:8080 来访问和管理 Sentinel 策略。
181+
182+
### 配置熔断规则
183+
>登录 Sentinel 控制台,为之前定义的资源名称(例如 your_api_resource_name)配置流控、降级、系统保护等策略。
184+
![202403141432483963.png](http://124.222.54.192:4000/public/upload/2024/03/14/202403141432483963.png)
185+
186+
### 编写降级处理逻辑
187+
> 如果在配置中指定了 fallbackUri,则需要在服务端实现对应的降级处理逻辑,当触发熔断时将执行这个逻辑。
188+
#### yaml配置
189+
> 在 Spring Cloud Gateway 的路由配置中,为 SentinelGatewayFilter 添加 fallbackUri 参数,指定一个本地处理熔断或降级的 URI。
190+
191+
```yaml
192+
spring:
193+
cloud:
194+
gateway:
195+
routes:
196+
- id: your_route_id
197+
uri: lb://your_service_id
198+
predicates:
199+
- Path=/your-api-path/**
200+
filters:
201+
- name: SentinelGatewayFilter
202+
args:
203+
resource: your_api_resource_name
204+
fallbackUri: forward:/fallback
205+
```
206+
#### 具体实现
207+
> 在您的 Spring Boot 应用中创建一个 Controller 或者 Endpoint 来处理这个 /fallback 请求。
208+
209+
```java
210+
@RestController
211+
public class FallbackController {
212+
213+
@GetMapping("/fallback")
214+
public Mono<String> fallback(ServerWebExchange exchange) {
215+
// 这里可以根据需要自定义降级返回的内容
216+
return Mono.just("Fallback response due to service unavailable.");
217+
}
218+
}
219+
```
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# SpringCloudGateway之统一鉴权篇
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# SpringCloudGateway之限流集成篇

0 commit comments

Comments
 (0)