1. Sentinel概述

Sentinel是阿里巴巴开源的分布式系统的流量防卫兵,以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。在Java应用中,Sentinel提供了丰富的API和注解,可以实现细粒度的流量控制、熔断降级、系统保护等功能。本文将详细介绍Sentinel的工作原理、使用场景、实现方法、性能优化技巧以及在Java实战中的应用。

1.1 Sentinel核心价值

  1. 流量控制: 精确控制请求流量,防止系统过载
  2. 熔断降级: 自动熔断异常服务,快速失败
  3. 系统保护: 保护系统稳定性,防止雪崩效应
  4. 实时监控: 提供丰富的监控指标和实时数据
  5. 规则管理: 支持动态规则配置和实时生效

1.2 Sentinel核心功能

  • 流量控制: QPS限流、并发线程数限流
  • 熔断降级: 慢调用比例、异常比例、异常数熔断
  • 系统负载保护: CPU使用率、平均RT、并发线程数
  • 热点参数限流: 针对热点参数进行限流
  • 集群流控: 分布式环境下的集群流量控制

1.3 Sentinel应用场景

  • 微服务治理: 服务间调用流量控制
  • API网关: 网关层面的流量控制
  • 数据库保护: 数据库访问流量控制
  • 缓存保护: 缓存访问流量控制
  • 第三方服务: 外部服务调用保护

2. Sentinel基础实现

2.1 Sentinel配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Sentinel配置类
* @author 运维实战
*/
@Configuration
@EnableConfigurationProperties(SentinelProperties.class)
public class SentinelConfig {

@Autowired
private SentinelProperties sentinelProperties;

/**
* 初始化Sentinel
*/
@PostConstruct
public void initSentinel() {
// 配置Sentinel控制台地址
System.setProperty("csp.sentinel.dashboard.server", sentinelProperties.getDashboardServer());
System.setProperty("csp.sentinel.api.port", String.valueOf(sentinelProperties.getApiPort()));

// 配置应用名称
System.setProperty("project.name", sentinelProperties.getProjectName());

// 配置日志目录
System.setProperty("csp.sentinel.log.dir", sentinelProperties.getLogDir());

logger.info("Sentinel初始化完成,控制台地址: {}", sentinelProperties.getDashboardServer());
}

/**
* Sentinel规则管理器
* @return 规则管理器
*/
@Bean
public SentinelRuleManager sentinelRuleManager() {
return new SentinelRuleManager();
}

/**
* Sentinel监控器
* @return 监控器
*/
@Bean
public SentinelMonitor sentinelMonitor() {
return new SentinelMonitor();
}

private static final Logger logger = LoggerFactory.getLogger(SentinelConfig.class);
}

2.2 Sentinel属性配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Sentinel属性配置
* @author 运维实战
*/
@Data
@ConfigurationProperties(prefix = "sentinel")
public class SentinelProperties {

/**
* 控制台地址
*/
private String dashboardServer = "localhost:8080";

/**
* API端口
*/
private int apiPort = 8719;

/**
* 项目名称
*/
private String projectName = "sentinel-demo";

/**
* 日志目录
*/
private String logDir = "./logs/sentinel";

/**
* 是否启用控制台
*/
private boolean enableDashboard = true;

/**
* 心跳间隔(毫秒)
*/
private long heartbeatInterval = 10000;

/**
* 规则持久化
*/
private boolean enableRulePersistence = false;

/**
* 规则持久化路径
*/
private String rulePersistencePath = "./rules";
}

2.3 基础流控服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* 基础流控服务
* @author 运维实战
*/
@Service
public class BasicFlowControlService {

private static final Logger logger = LoggerFactory.getLogger(BasicFlowControlService.class);

/**
* 基础流控示例
* @param resource 资源名称
* @param qps 每秒请求数限制
* @return 处理结果
*/
public String basicFlowControl(String resource, int qps) {
// 定义资源
try (Entry entry = SphU.entry(resource)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 流控异常处理
logger.warn("资源 {} 被流控,QPS限制: {}", resource, qps);
return "请求被流控,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 并发流控示例
* @param resource 资源名称
* @param maxConcurrency 最大并发数
* @return 处理结果
*/
public String concurrencyFlowControl(String resource, int maxConcurrency) {
// 定义资源
try (Entry entry = SphU.entry(resource, EntryType.IN, 1, resource)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 流控异常处理
logger.warn("资源 {} 被并发流控,最大并发数: {}", resource, maxConcurrency);
return "系统繁忙,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 关联流控示例
* @param resource 资源名称
* @param associatedResource 关联资源
* @return 处理结果
*/
public String associatedFlowControl(String resource, String associatedResource) {
// 定义资源
try (Entry entry = SphU.entry(resource)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 流控异常处理
logger.warn("资源 {} 被关联流控,关联资源: {}", resource, associatedResource);
return "关联资源繁忙,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 链路流控示例
* @param resource 资源名称
* @param origin 调用来源
* @return 处理结果
*/
public String linkFlowControl(String resource, String origin) {
// 定义资源
try (Entry entry = SphU.entry(resource, EntryType.IN, 1, origin)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 流控异常处理
logger.warn("资源 {} 被链路流控,调用来源: {}", resource, origin);
return "调用来源受限,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 执行业务逻辑
* @param resource 资源名称
* @return 处理结果
*/
private String executeBusinessLogic(String resource) {
// 模拟业务处理
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "业务处理完成: " + resource;
}
}

2.4 熔断降级服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* 熔断降级服务
* @author 运维实战
*/
@Service
public class CircuitBreakerService {

private static final Logger logger = LoggerFactory.getLogger(CircuitBreakerService.class);

/**
* 慢调用比例熔断示例
* @param resource 资源名称
* @param slowRatio 慢调用比例阈值
* @param minRequestCount 最小请求数
* @param timeWindow 时间窗口
* @return 处理结果
*/
public String slowCallRatioCircuitBreaker(String resource, double slowRatio, int minRequestCount, int timeWindow) {
try (Entry entry = SphU.entry(resource)) {
// 执行业务逻辑
return executeBusinessLogic(resource, 200); // 模拟慢调用
} catch (BlockException e) {
// 熔断异常处理
logger.warn("资源 {} 被熔断,慢调用比例: {}, 最小请求数: {}, 时间窗口: {}ms",
resource, slowRatio, minRequestCount, timeWindow);
return "服务熔断,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 异常比例熔断示例
* @param resource 资源名称
* @param exceptionRatio 异常比例阈值
* @param minRequestCount 最小请求数
* @param timeWindow 时间窗口
* @return 处理结果
*/
public String exceptionRatioCircuitBreaker(String resource, double exceptionRatio, int minRequestCount, int timeWindow) {
try (Entry entry = SphU.entry(resource)) {
// 模拟异常情况
if (Math.random() < 0.3) {
throw new RuntimeException("模拟业务异常");
}

// 执行业务逻辑
return executeBusinessLogic(resource, 100);
} catch (BlockException e) {
// 熔断异常处理
logger.warn("资源 {} 被熔断,异常比例: {}, 最小请求数: {}, 时间窗口: {}ms",
resource, exceptionRatio, minRequestCount, timeWindow);
return "服务熔断,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 异常数熔断示例
* @param resource 资源名称
* @param exceptionCount 异常数阈值
* @param minRequestCount 最小请求数
* @param timeWindow 时间窗口
* @return 处理结果
*/
public String exceptionCountCircuitBreaker(String resource, int exceptionCount, int minRequestCount, int timeWindow) {
try (Entry entry = SphU.entry(resource)) {
// 模拟异常情况
if (Math.random() < 0.2) {
throw new RuntimeException("模拟业务异常");
}

// 执行业务逻辑
return executeBusinessLogic(resource, 100);
} catch (BlockException e) {
// 熔断异常处理
logger.warn("资源 {} 被熔断,异常数: {}, 最小请求数: {}, 时间窗口: {}ms",
resource, exceptionCount, minRequestCount, timeWindow);
return "服务熔断,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 执行业务逻辑
* @param resource 资源名称
* @param delay 延迟时间
* @return 处理结果
*/
private String executeBusinessLogic(String resource, int delay) {
// 模拟业务处理
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "业务处理完成: " + resource;
}
}

2.5 系统保护服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* 系统保护服务
* @author 运维实战
*/
@Service
public class SystemProtectionService {

private static final Logger logger = LoggerFactory.getLogger(SystemProtectionService.class);

/**
* CPU使用率保护示例
* @param resource 资源名称
* @param cpuUsage CPU使用率阈值
* @return 处理结果
*/
public String cpuUsageProtection(String resource, double cpuUsage) {
try (Entry entry = SphU.entry(resource)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 系统保护异常处理
logger.warn("资源 {} 被系统保护,CPU使用率阈值: {}%", resource, cpuUsage);
return "系统负载过高,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 平均RT保护示例
* @param resource 资源名称
* @param avgRt 平均RT阈值
* @return 处理结果
*/
public String avgRtProtection(String resource, int avgRt) {
try (Entry entry = SphU.entry(resource)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 系统保护异常处理
logger.warn("资源 {} 被系统保护,平均RT阈值: {}ms", resource, avgRt);
return "系统响应时间过长,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 并发线程数保护示例
* @param resource 资源名称
* @param maxConcurrency 最大并发线程数
* @return 处理结果
*/
public String concurrencyProtection(String resource, int maxConcurrency) {
try (Entry entry = SphU.entry(resource)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 系统保护异常处理
logger.warn("资源 {} 被系统保护,最大并发线程数: {}", resource, maxConcurrency);
return "系统并发过高,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 系统QPS保护示例
* @param resource 资源名称
* @param maxQps 最大QPS
* @return 处理结果
*/
public String systemQpsProtection(String resource, int maxQps) {
try (Entry entry = SphU.entry(resource)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 系统保护异常处理
logger.warn("资源 {} 被系统保护,最大QPS: {}", resource, maxQps);
return "系统QPS过高,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 执行业务逻辑
* @param resource 资源名称
* @return 处理结果
*/
private String executeBusinessLogic(String resource) {
// 模拟业务处理
try {
Thread.sleep(150);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "业务处理完成: " + resource;
}
}

3. 高级功能实现

3.1 热点参数限流服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* 热点参数限流服务
* @author 运维实战
*/
@Service
public class HotParamFlowControlService {

private static final Logger logger = LoggerFactory.getLogger(HotParamFlowControlService.class);

/**
* 热点参数限流示例
* @param userId 用户ID
* @param productId 产品ID
* @return 处理结果
*/
public String hotParamFlowControl(String userId, String productId) {
try (Entry entry = SphU.entry("hotParamResource", EntryType.IN, 1, userId, productId)) {
// 执行业务逻辑
return executeBusinessLogic(userId, productId);
} catch (BlockException e) {
// 热点参数限流异常处理
logger.warn("热点参数限流,用户ID: {}, 产品ID: {}", userId, productId);
return "热点参数访问受限,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: userId={}, productId={}", userId, productId, e);
return "业务处理失败";
}
}

/**
* 热点参数限流(带参数索引)
* @param userId 用户ID
* @param productId 产品ID
* @param categoryId 分类ID
* @return 处理结果
*/
public String hotParamFlowControlWithIndex(String userId, String productId, String categoryId) {
try (Entry entry = SphU.entry("hotParamResourceWithIndex", EntryType.IN, 1,
new Object[]{userId, productId, categoryId}, new int[]{0, 1})) {
// 执行业务逻辑
return executeBusinessLogic(userId, productId, categoryId);
} catch (BlockException e) {
// 热点参数限流异常处理
logger.warn("热点参数限流,用户ID: {}, 产品ID: {}, 分类ID: {}", userId, productId, categoryId);
return "热点参数访问受限,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: userId={}, productId={}, categoryId={}",
userId, productId, categoryId, e);
return "业务处理失败";
}
}

/**
* 热点参数限流(带参数值)
* @param userId 用户ID
* @param productId 产品ID
* @return 处理结果
*/
public String hotParamFlowControlWithValue(String userId, String productId) {
try (Entry entry = SphU.entry("hotParamResourceWithValue", EntryType.IN, 1,
new Object[]{userId, productId}, new int[]{0, 1},
new String[]{"user123", "product456"})) {
// 执行业务逻辑
return executeBusinessLogic(userId, productId);
} catch (BlockException e) {
// 热点参数限流异常处理
logger.warn("热点参数限流,用户ID: {}, 产品ID: {}", userId, productId);
return "热点参数访问受限,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: userId={}, productId={}", userId, productId, e);
return "业务处理失败";
}
}

/**
* 执行业务逻辑
* @param userId 用户ID
* @param productId 产品ID
* @return 处理结果
*/
private String executeBusinessLogic(String userId, String productId) {
// 模拟业务处理
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "业务处理完成: userId=" + userId + ", productId=" + productId;
}

/**
* 执行业务逻辑
* @param userId 用户ID
* @param productId 产品ID
* @param categoryId 分类ID
* @return 处理结果
*/
private String executeBusinessLogic(String userId, String productId, String categoryId) {
// 模拟业务处理
try {
Thread.sleep(120);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "业务处理完成: userId=" + userId + ", productId=" + productId + ", categoryId=" + categoryId;
}
}

3.2 集群流控服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* 集群流控服务
* @author 运维实战
*/
@Service
public class ClusterFlowControlService {

private static final Logger logger = LoggerFactory.getLogger(ClusterFlowControlService.class);

/**
* 集群流控示例
* @param resource 资源名称
* @param clusterMode 集群模式
* @return 处理结果
*/
public String clusterFlowControl(String resource, int clusterMode) {
try (Entry entry = SphU.entry(resource, EntryType.IN, 1, clusterMode)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 集群流控异常处理
logger.warn("资源 {} 被集群流控,集群模式: {}", resource, clusterMode);
return "集群流量受限,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 集群流控(带阈值)
* @param resource 资源名称
* @param threshold 阈值
* @return 处理结果
*/
public String clusterFlowControlWithThreshold(String resource, double threshold) {
try (Entry entry = SphU.entry(resource, EntryType.IN, 1, threshold)) {
// 执行业务逻辑
return executeBusinessLogic(resource);
} catch (BlockException e) {
// 集群流控异常处理
logger.warn("资源 {} 被集群流控,阈值: {}", resource, threshold);
return "集群流量受限,请稍后重试";
} catch (Exception e) {
// 其他异常处理
logger.error("业务逻辑执行失败: {}", resource, e);
return "业务处理失败";
}
}

/**
* 执行业务逻辑
* @param resource 资源名称
* @return 处理结果
*/
private String executeBusinessLogic(String resource) {
// 模拟业务处理
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "业务处理完成: " + resource;
}
}

3.3 Sentinel规则管理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/**
* Sentinel规则管理器
* @author 运维实战
*/
@Component
public class SentinelRuleManager {

private static final Logger logger = LoggerFactory.getLogger(SentinelRuleManager.class);

/**
* 创建流控规则
* @param resource 资源名称
* @param qps 每秒请求数
* @return 流控规则
*/
public FlowRule createFlowRule(String resource, int qps) {
FlowRule rule = new FlowRule();
rule.setResource(resource);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(qps);
rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);

logger.info("创建流控规则: resource={}, qps={}", resource, qps);
return rule;
}

/**
* 创建并发流控规则
* @param resource 资源名称
* @param maxConcurrency 最大并发数
* @return 流控规则
*/
public FlowRule createConcurrencyFlowRule(String resource, int maxConcurrency) {
FlowRule rule = new FlowRule();
rule.setResource(resource);
rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
rule.setCount(maxConcurrency);
rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);

logger.info("创建并发流控规则: resource={}, maxConcurrency={}", resource, maxConcurrency);
return rule;
}

/**
* 创建熔断规则
* @param resource 资源名称
* @param slowRatio 慢调用比例
* @param minRequestCount 最小请求数
* @param timeWindow 时间窗口
* @return 熔断规则
*/
public DegradeRule createDegradeRule(String resource, double slowRatio, int minRequestCount, int timeWindow) {
DegradeRule rule = new DegradeRule();
rule.setResource(resource);
rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
rule.setCount(200); // RT阈值
rule.setTimeWindow(timeWindow);
rule.setMinRequestAmount(minRequestCount);
rule.setSlowRatioThreshold(slowRatio);

logger.info("创建熔断规则: resource={}, slowRatio={}, minRequestCount={}, timeWindow={}",
resource, slowRatio, minRequestCount, timeWindow);
return rule;
}

/**
* 创建系统保护规则
* @param resource 资源名称
* @param cpuUsage CPU使用率阈值
* @return 系统保护规则
*/
public SystemRule createSystemRule(String resource, double cpuUsage) {
SystemRule rule = new SystemRule();
rule.setResource(resource);
rule.setGrade(RuleConstant.SYSTEM_GRADE_CPU_USAGE);
rule.setCount(cpuUsage);

logger.info("创建系统保护规则: resource={}, cpuUsage={}", resource, cpuUsage);
return rule;
}

/**
* 创建热点参数限流规则
* @param resource 资源名称
* @param paramIndex 参数索引
* @param qps 每秒请求数
* @return 热点参数限流规则
*/
public ParamFlowRule createHotParamRule(String resource, int paramIndex, int qps) {
ParamFlowRule rule = new ParamFlowRule();
rule.setResource(resource);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(qps);
rule.setParamIdx(paramIndex);

logger.info("创建热点参数限流规则: resource={}, paramIndex={}, qps={}", resource, paramIndex, qps);
return rule;
}

/**
* 加载规则
* @param rules 规则列表
*/
public void loadRules(List<FlowRule> rules) {
try {
FlowRuleManager.loadRules(rules);
logger.info("流控规则加载成功,规则数量: {}", rules.size());
} catch (Exception e) {
logger.error("流控规则加载失败", e);
}
}

/**
* 加载熔断规则
* @param rules 熔断规则列表
*/
public void loadDegradeRules(List<DegradeRule> rules) {
try {
DegradeRuleManager.loadRules(rules);
logger.info("熔断规则加载成功,规则数量: {}", rules.size());
} catch (Exception e) {
logger.error("熔断规则加载失败", e);
}
}

/**
* 加载系统保护规则
* @param rules 系统保护规则列表
*/
public void loadSystemRules(List<SystemRule> rules) {
try {
SystemRuleManager.loadRules(rules);
logger.info("系统保护规则加载成功,规则数量: {}", rules.size());
} catch (Exception e) {
logger.error("系统保护规则加载失败", e);
}
}

/**
* 加载热点参数限流规则
* @param rules 热点参数限流规则列表
*/
public void loadParamFlowRules(List<ParamFlowRule> rules) {
try {
ParamFlowRuleManager.loadRules(rules);
logger.info("热点参数限流规则加载成功,规则数量: {}", rules.size());
} catch (Exception e) {
logger.error("热点参数限流规则加载失败", e);
}
}
}

3.4 Sentinel监控器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/**
* Sentinel监控器
* @author 运维实战
*/
@Component
public class SentinelMonitor {

private static final Logger logger = LoggerFactory.getLogger(SentinelMonitor.class);

/**
* 获取资源统计信息
* @param resource 资源名称
* @return 资源统计信息
*/
public ResourceStatistics getResourceStatistics(String resource) {
try {
Node node = ClusterNodeBuilder.buildClusterNode(resource);

ResourceStatistics statistics = new ResourceStatistics();
statistics.setResource(resource);
statistics.setPassQps(node.passQps());
statistics.setBlockQps(node.blockQps());
statistics.setTotalQps(node.totalQps());
statistics.setAvgRt(node.avgRt());
statistics.setConcurrency(node.curThreadNum());
statistics.setTimestamp(System.currentTimeMillis());

return statistics;

} catch (Exception e) {
logger.error("获取资源统计信息失败: resource={}", resource, e);
return null;
}
}

/**
* 获取所有资源统计信息
* @return 所有资源统计信息
*/
public Map<String, ResourceStatistics> getAllResourceStatistics() {
Map<String, ResourceStatistics> statisticsMap = new HashMap<>();

try {
// 获取所有资源
Set<String> resources = ResourceUtils.getResourceNames();

for (String resource : resources) {
ResourceStatistics statistics = getResourceStatistics(resource);
if (statistics != null) {
statisticsMap.put(resource, statistics);
}
}

} catch (Exception e) {
logger.error("获取所有资源统计信息失败", e);
}

return statisticsMap;
}

/**
* 获取系统指标
* @return 系统指标
*/
public SystemMetrics getSystemMetrics() {
try {
SystemMetrics metrics = new SystemMetrics();
metrics.setCpuUsage(getCpuUsage());
metrics.setMemoryUsage(getMemoryUsage());
metrics.setLoadAverage(getLoadAverage());
metrics.setTimestamp(System.currentTimeMillis());

return metrics;

} catch (Exception e) {
logger.error("获取系统指标失败", e);
return null;
}
}

/**
* 定期监控资源状态
*/
@Scheduled(fixedRate = 30000) // 每30秒监控一次
public void monitorResourceStatus() {
try {
Map<String, ResourceStatistics> statisticsMap = getAllResourceStatistics();

for (Map.Entry<String, ResourceStatistics> entry : statisticsMap.entrySet()) {
String resource = entry.getKey();
ResourceStatistics statistics = entry.getValue();

logger.info("资源监控: resource={}, passQps={}, blockQps={}, totalQps={}, avgRt={}, concurrency={}",
resource, statistics.getPassQps(), statistics.getBlockQps(),
statistics.getTotalQps(), statistics.getAvgRt(), statistics.getConcurrency());

// 检查异常情况
if (statistics.getBlockQps() > 0) {
logger.warn("资源被流控: resource={}, blockQps={}", resource, statistics.getBlockQps());
}

if (statistics.getAvgRt() > 1000) {
logger.warn("资源响应时间过长: resource={}, avgRt={}", resource, statistics.getAvgRt());
}

if (statistics.getConcurrency() > 100) {
logger.warn("资源并发数过高: resource={}, concurrency={}", resource, statistics.getConcurrency());
}
}

} catch (Exception e) {
logger.error("资源状态监控失败", e);
}
}

/**
* 获取CPU使用率
* @return CPU使用率
*/
private double getCpuUsage() {
try {
com.sun.management.OperatingSystemMXBean osBean =
(com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
return osBean.getProcessCpuLoad() * 100;
} catch (Exception e) {
return 0.0;
}
}

/**
* 获取内存使用率
* @return 内存使用率
*/
private double getMemoryUsage() {
try {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
return (double) heapUsage.getUsed() / heapUsage.getMax() * 100;
} catch (Exception e) {
return 0.0;
}
}

/**
* 获取系统负载
* @return 系统负载
*/
private double getLoadAverage() {
try {
OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
return osBean.getSystemLoadAverage();
} catch (Exception e) {
return 0.0;
}
}
}

3.5 资源统计信息类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 资源统计信息类
* @author 运维实战
*/
@Data
public class ResourceStatistics {

private String resource;
private double passQps;
private double blockQps;
private double totalQps;
private double avgRt;
private int concurrency;
private long timestamp;

public ResourceStatistics() {
this.timestamp = System.currentTimeMillis();
}

/**
* 获取通过率
* @return 通过率
*/
public double getPassRate() {
if (totalQps == 0) return 0.0;
return passQps / totalQps * 100;
}

/**
* 获取阻塞率
* @return 阻塞率
*/
public double getBlockRate() {
if (totalQps == 0) return 0.0;
return blockQps / totalQps * 100;
}

/**
* 是否健康
* @return 是否健康
*/
public boolean isHealthy() {
return blockRate() < 10 && avgRt < 1000 && concurrency < 100;
}
}

3.6 系统指标类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 系统指标类
* @author 运维实战
*/
@Data
public class SystemMetrics {

private double cpuUsage;
private double memoryUsage;
private double loadAverage;
private long timestamp;

public SystemMetrics() {
this.timestamp = System.currentTimeMillis();
}

/**
* 是否健康
* @return 是否健康
*/
public boolean isHealthy() {
return cpuUsage < 80 && memoryUsage < 80 && loadAverage < 5;
}
}

4. Sentinel注解和AOP

4.1 Sentinel注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Sentinel注解
* @author 运维实战
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SentinelResource {

/**
* 资源名称
*/
String value() default "";

/**
* 入口类型
*/
EntryType entryType() default EntryType.OUT;

/**
* 资源类型
*/
int resourceType() default 0;

/**
* 异常处理函数
*/
String blockHandler() default "";

/**
* 异常处理函数类
*/
Class<?> blockHandlerClass() default void.class;

/**
* fallback函数
*/
String fallback() default "";

/**
* fallback函数类
*/
Class<?> fallbackClass() default void.class;

/**
* 默认fallback函数
*/
String defaultFallback() default "";

/**
* 默认fallback函数类
*/
Class<?> defaultFallbackClass() default void.class;

/**
* 异常类型
*/
Class<? extends Throwable>[] exceptionsToTrace() default {Throwable.class};

/**
* 异常类型忽略
*/
Class<? extends Throwable>[] exceptionsToIgnore() default {};
}

4.2 Sentinel AOP切面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/**
* Sentinel AOP切面
* @author 运维实战
*/
@Aspect
@Component
public class SentinelAspect {

private static final Logger logger = LoggerFactory.getLogger(SentinelAspect.class);

/**
* Sentinel切点
*/
@Pointcut("@annotation(sentinelResource)")
public void sentinelPointcut(SentinelResource sentinelResource) {}

/**
* Sentinel环绕通知
* @param joinPoint 连接点
* @param sentinelResource Sentinel注解
* @return 执行结果
* @throws Throwable 异常
*/
@Around("sentinelPointcut(sentinelResource)")
public Object around(ProceedingJoinPoint joinPoint, SentinelResource sentinelResource) throws Throwable {
String resource = generateResourceName(joinPoint, sentinelResource);

try {
// 定义资源
try (Entry entry = SphU.entry(resource, sentinelResource.entryType())) {
// 执行业务逻辑
return joinPoint.proceed();
} catch (BlockException e) {
// 流控异常处理
return handleBlockException(joinPoint, sentinelResource, e);
}
} catch (Throwable e) {
// 其他异常处理
return handleFallback(joinPoint, sentinelResource, e);
}
}

/**
* 处理流控异常
* @param joinPoint 连接点
* @param sentinelResource Sentinel注解
* @param e 流控异常
* @return 处理结果
*/
private Object handleBlockException(ProceedingJoinPoint joinPoint, SentinelResource sentinelResource, BlockException e) {
String resource = generateResourceName(joinPoint, sentinelResource);
logger.warn("资源被流控: resource={}, exception={}", resource, e.getClass().getSimpleName());

// 调用blockHandler
if (!sentinelResource.blockHandler().isEmpty()) {
return invokeBlockHandler(joinPoint, sentinelResource, e);
}

// 调用默认fallback
if (!sentinelResource.defaultFallback().isEmpty()) {
return invokeDefaultFallback(joinPoint, sentinelResource, e);
}

// 默认处理
return "请求被流控,请稍后重试";
}

/**
* 处理fallback
* @param joinPoint 连接点
* @param sentinelResource Sentinel注解
* @param e 异常
* @return 处理结果
*/
private Object handleFallback(ProceedingJoinPoint joinPoint, SentinelResource sentinelResource, Throwable e) {
String resource = generateResourceName(joinPoint, sentinelResource);
logger.error("业务逻辑执行失败: resource={}", resource, e);

// 调用fallback
if (!sentinelResource.fallback().isEmpty()) {
return invokeFallback(joinPoint, sentinelResource, e);
}

// 调用默认fallback
if (!sentinelResource.defaultFallback().isEmpty()) {
return invokeDefaultFallback(joinPoint, sentinelResource, e);
}

// 默认处理
return "业务处理失败";
}

/**
* 调用blockHandler
* @param joinPoint 连接点
* @param sentinelResource Sentinel注解
* @param e 流控异常
* @return 处理结果
*/
private Object invokeBlockHandler(ProceedingJoinPoint joinPoint, SentinelResource sentinelResource, BlockException e) {
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Class<?> targetClass = joinPoint.getTarget().getClass();

Method blockHandlerMethod = findMethod(targetClass, sentinelResource.blockHandler(),
signature.getParameterTypes(), BlockException.class);

if (blockHandlerMethod != null) {
Object[] args = joinPoint.getArgs();
Object[] newArgs = new Object[args.length + 1];
System.arraycopy(args, 0, newArgs, 0, args.length);
newArgs[args.length] = e;

return blockHandlerMethod.invoke(joinPoint.getTarget(), newArgs);
}
} catch (Exception ex) {
logger.error("调用blockHandler失败", ex);
}

return "请求被流控,请稍后重试";
}

/**
* 调用fallback
* @param joinPoint 连接点
* @param sentinelResource Sentinel注解
* @param e 异常
* @return 处理结果
*/
private Object invokeFallback(ProceedingJoinPoint joinPoint, SentinelResource sentinelResource, Throwable e) {
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Class<?> targetClass = joinPoint.getTarget().getClass();

Method fallbackMethod = findMethod(targetClass, sentinelResource.fallback(),
signature.getParameterTypes(), Throwable.class);

if (fallbackMethod != null) {
Object[] args = joinPoint.getArgs();
Object[] newArgs = new Object[args.length + 1];
System.arraycopy(args, 0, newArgs, 0, args.length);
newArgs[args.length] = e;

return fallbackMethod.invoke(joinPoint.getTarget(), newArgs);
}
} catch (Exception ex) {
logger.error("调用fallback失败", ex);
}

return "业务处理失败";
}

/**
* 调用默认fallback
* @param joinPoint 连接点
* @param sentinelResource Sentinel注解
* @param e 异常
* @return 处理结果
*/
private Object invokeDefaultFallback(ProceedingJoinPoint joinPoint, SentinelResource sentinelResource, Throwable e) {
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Class<?> targetClass = joinPoint.getTarget().getClass();

Method defaultFallbackMethod = findMethod(targetClass, sentinelResource.defaultFallback(),
signature.getParameterTypes(), Throwable.class);

if (defaultFallbackMethod != null) {
Object[] args = joinPoint.getArgs();
Object[] newArgs = new Object[args.length + 1];
System.arraycopy(args, 0, newArgs, 0, args.length);
newArgs[args.length] = e;

return defaultFallbackMethod.invoke(joinPoint.getTarget(), newArgs);
}
} catch (Exception ex) {
logger.error("调用默认fallback失败", ex);
}

return "业务处理失败";
}

/**
* 查找方法
* @param targetClass 目标类
* @param methodName 方法名
* @param parameterTypes 参数类型
* @param additionalType 额外参数类型
* @return 方法
*/
private Method findMethod(Class<?> targetClass, String methodName, Class<?>[] parameterTypes, Class<?> additionalType) {
try {
Class<?>[] newParameterTypes = new Class<?>[parameterTypes.length + 1];
System.arraycopy(parameterTypes, 0, newParameterTypes, 0, parameterTypes.length);
newParameterTypes[parameterTypes.length] = additionalType;

return targetClass.getMethod(methodName, newParameterTypes);
} catch (NoSuchMethodException e) {
return null;
}
}

/**
* 生成资源名称
* @param joinPoint 连接点
* @param sentinelResource Sentinel注解
* @return 资源名称
*/
private String generateResourceName(ProceedingJoinPoint joinPoint, SentinelResource sentinelResource) {
if (!sentinelResource.value().isEmpty()) {
return sentinelResource.value();
}

// 生成默认资源名称
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String className = signature.getDeclaringType().getSimpleName();
String methodName = signature.getName();

return className + "." + methodName;
}
}

5. 实际应用示例

5.1 使用Sentinel注解的服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* 使用Sentinel注解的服务
* @author 运维实战
*/
@Service
public class SentinelExampleService {

private static final Logger logger = LoggerFactory.getLogger(SentinelExampleService.class);

/**
* 基础流控示例
* @param data 数据
* @return 处理结果
*/
@SentinelResource(value = "example.basic", blockHandler = "handleBlock", fallback = "handleFallback")
public String basicFlowControl(String data) {
logger.info("执行基础流控示例: {}", data);

// 模拟业务处理
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "基础流控处理完成: " + data;
}

/**
* 熔断降级示例
* @param data 数据
* @return 处理结果
*/
@SentinelResource(value = "example.circuitBreaker", blockHandler = "handleBlock", fallback = "handleFallback")
public String circuitBreakerExample(String data) {
logger.info("执行熔断降级示例: {}", data);

// 模拟异常情况
if (Math.random() < 0.3) {
throw new RuntimeException("模拟业务异常");
}

// 模拟业务处理
try {
Thread.sleep(150);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "熔断降级处理完成: " + data;
}

/**
* 热点参数限流示例
* @param userId 用户ID
* @param productId 产品ID
* @return 处理结果
*/
@SentinelResource(value = "example.hotParam", blockHandler = "handleBlock", fallback = "handleFallback")
public String hotParamExample(String userId, String productId) {
logger.info("执行热点参数限流示例: userId={}, productId={}", userId, productId);

// 模拟业务处理
try {
Thread.sleep(120);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "热点参数处理完成: userId=" + userId + ", productId=" + productId;
}

/**
* 系统保护示例
* @param data 数据
* @return 处理结果
*/
@SentinelResource(value = "example.systemProtection", blockHandler = "handleBlock", fallback = "handleFallback")
public String systemProtectionExample(String data) {
logger.info("执行系统保护示例: {}", data);

// 模拟业务处理
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

return "系统保护处理完成: " + data;
}

/**
* 流控异常处理
* @param data 数据
* @param e 流控异常
* @return 处理结果
*/
public String handleBlock(String data, BlockException e) {
logger.warn("流控异常处理: data={}, exception={}", data, e.getClass().getSimpleName());
return "请求被流控,请稍后重试";
}

/**
* 业务异常处理
* @param data 数据
* @param e 异常
* @return 处理结果
*/
public String handleFallback(String data, Throwable e) {
logger.error("业务异常处理: data={}", data, e);
return "业务处理失败,请稍后重试";
}
}

5.2 Sentinel测试控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/**
* Sentinel测试控制器
* @author 运维实战
*/
@RestController
@RequestMapping("/api/sentinel/test")
public class SentinelTestController {

@Autowired
private SentinelExampleService sentinelExampleService;

@Autowired
private SentinelRuleManager sentinelRuleManager;

@Autowired
private SentinelMonitor sentinelMonitor;

private static final Logger logger = LoggerFactory.getLogger(SentinelTestController.class);

/**
* 基础流控测试
* @param data 测试数据
* @return 测试结果
*/
@GetMapping("/basic")
public ResponseEntity<Map<String, String>> testBasicFlowControl(@RequestParam String data) {
try {
String result = sentinelExampleService.basicFlowControl(data);

Map<String, String> response = new HashMap<>();
response.put("status", "SUCCESS");
response.put("result", result);
response.put("timestamp", String.valueOf(System.currentTimeMillis()));

return ResponseEntity.ok(response);

} catch (Exception e) {
logger.error("基础流控测试失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 熔断降级测试
* @param data 测试数据
* @return 测试结果
*/
@GetMapping("/circuitBreaker")
public ResponseEntity<Map<String, String>> testCircuitBreaker(@RequestParam String data) {
try {
String result = sentinelExampleService.circuitBreakerExample(data);

Map<String, String> response = new HashMap<>();
response.put("status", "SUCCESS");
response.put("result", result);
response.put("timestamp", String.valueOf(System.currentTimeMillis()));

return ResponseEntity.ok(response);

} catch (Exception e) {
logger.error("熔断降级测试失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 热点参数限流测试
* @param userId 用户ID
* @param productId 产品ID
* @return 测试结果
*/
@GetMapping("/hotParam")
public ResponseEntity<Map<String, String>> testHotParam(@RequestParam String userId, @RequestParam String productId) {
try {
String result = sentinelExampleService.hotParamExample(userId, productId);

Map<String, String> response = new HashMap<>();
response.put("status", "SUCCESS");
response.put("result", result);
response.put("timestamp", String.valueOf(System.currentTimeMillis()));

return ResponseEntity.ok(response);

} catch (Exception e) {
logger.error("热点参数限流测试失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 系统保护测试
* @param data 测试数据
* @return 测试结果
*/
@GetMapping("/systemProtection")
public ResponseEntity<Map<String, String>> testSystemProtection(@RequestParam String data) {
try {
String result = sentinelExampleService.systemProtectionExample(data);

Map<String, String> response = new HashMap<>();
response.put("status", "SUCCESS");
response.put("result", result);
response.put("timestamp", String.valueOf(System.currentTimeMillis()));

return ResponseEntity.ok(response);

} catch (Exception e) {
logger.error("系统保护测试失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取资源统计信息
* @param resource 资源名称
* @return 资源统计信息
*/
@GetMapping("/statistics/{resource}")
public ResponseEntity<ResourceStatistics> getResourceStatistics(@PathVariable String resource) {
try {
ResourceStatistics statistics = sentinelMonitor.getResourceStatistics(resource);
if (statistics != null) {
return ResponseEntity.ok(statistics);
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
logger.error("获取资源统计信息失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取所有资源统计信息
* @return 所有资源统计信息
*/
@GetMapping("/statistics")
public ResponseEntity<Map<String, ResourceStatistics>> getAllResourceStatistics() {
try {
Map<String, ResourceStatistics> statisticsMap = sentinelMonitor.getAllResourceStatistics();
return ResponseEntity.ok(statisticsMap);
} catch (Exception e) {
logger.error("获取所有资源统计信息失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取系统指标
* @return 系统指标
*/
@GetMapping("/systemMetrics")
public ResponseEntity<SystemMetrics> getSystemMetrics() {
try {
SystemMetrics metrics = sentinelMonitor.getSystemMetrics();
if (metrics != null) {
return ResponseEntity.ok(metrics);
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
logger.error("获取系统指标失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}

6. 总结

6.1 Sentinel最佳实践

  1. 合理设置流控规则: 根据业务需求和系统容量设置流控规则
  2. 选择合适的熔断策略: 根据业务特点选择慢调用比例、异常比例等熔断策略
  3. 监控资源状态: 实时监控资源状态和性能指标
  4. 动态调整规则: 根据负载情况动态调整流控规则
  5. 异常处理: 实现完善的异常处理和降级策略

6.2 性能优化建议

  • 预热机制: 使用预热机制平滑启动流控
  • 集群流控: 在分布式环境中使用集群流控
  • 监控告警: 建立完善的监控和告警机制
  • 规则持久化: 使用规则持久化避免规则丢失
  • 异步处理: 使用异步处理提升系统响应性能

6.3 运维管理要点

  • 实时监控: 监控资源状态和性能指标
  • 动态调整: 根据负载情况动态调整流控规则
  • 异常处理: 建立异常处理和告警机制
  • 日志管理: 完善日志记录和分析
  • 性能调优: 根据监控数据优化流控规则

通过本文的Sentinel Java实战指南,您可以掌握流控原理、熔断降级、系统保护、热点参数限流以及在企业级应用中的最佳实践,构建高效、稳定的流量控制系统!