完成学习事务

This commit is contained in:
2026-03-03 13:14:15 +08:00
parent 5fb6350763
commit 2a79fca22c
17 changed files with 310 additions and 17 deletions

View File

@@ -43,5 +43,16 @@
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- Sentinel 网关适配依赖(关键) -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,40 @@
package cn.mayiming.Config;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreakerStrategy;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* Sentinel 熔断规则配置
* 为下游服务配置熔断策略
*/
@Configuration
public class SentinelDegradeConfig {
/**
* 初始化熔断规则
* @PostConstructSpring 容器启动后执行
*/
@PostConstruct
public void initDegradeRules() {
List<DegradeRule> rules = new ArrayList<>();
DegradeRule orderServiceRule = new DegradeRule();
orderServiceRule.setResource("order-service"); // 网关路由ID/服务名
// 关键:改为慢请求比例触发熔断
orderServiceRule.setCount(3000); // 慢请求阈值3000毫秒3秒超过3秒即为慢请求
orderServiceRule.setSlowRatioThreshold(0.5); // 慢请求比例阈值50%超过50%的请求是慢请求则触发熔断)
orderServiceRule.setTimeWindow(10); // 熔断后保持打开状态10秒
orderServiceRule.setMinRequestAmount(5); // 最小请求数累计5次请求后才计算慢请求比例
rules.add(orderServiceRule);
DegradeRuleManager.loadRules(rules);
}
}

View File

@@ -1,5 +1,5 @@
server:
port: 8080
port: 8081
spring:
application:
@@ -44,6 +44,21 @@ spring:
# 按 IP 限流(默认)
key-resolver: "#{@ipKeyResolver}"
sentinel:
# Sentinel 控制台地址(如果启动了控制台,用于可视化配置)
transport:
dashboard: localhost:8080 # Sentinel 控制台端口默认8080
port: 8719 # 客户端和控制台通信的端口
# 网关熔断配置
gateway:
enabled: true # 开启 Sentinel 网关适配
# 熔断后默认的降级响应
fallback:
mode: response # 降级方式:返回自定义响应
response-status: 503 # 降级响应状态码
response-body: "{\"code\":503,\"msg\":\"服务暂时不可用,请稍后重试\",\"data\":null}" # 降级响应体
response-content-type: application/json
# Nacos 注册
nacos:
discovery: