1. RateLimiter限流概述

Guava的RateLimiter是Google Guava库中提供的高性能限流工具,基于令牌桶算法实现,可以有效控制系统的请求频率,防止系统过载。在Java应用中,合理使用RateLimiter可以实现API限流、数据库访问限流、外部服务调用限流等功能。本文将详细介绍RateLimiter的工作原理、使用场景、实现方法、性能优化技巧以及在Java实战中的应用。

1.1 RateLimiter核心价值

  1. 流量控制: 精确控制请求频率和并发数量
  2. 系统保护: 防止系统过载和资源耗尽
  3. 性能优化: 通过限流提升系统稳定性
  4. 平滑处理: 实现平滑的流量控制
  5. 灵活配置: 支持动态调整限流参数

1.2 限流算法对比

  • 令牌桶算法: RateLimiter默认实现,支持突发流量
  • 漏桶算法: 固定速率输出,平滑处理
  • 滑动窗口: 基于时间窗口的限流
  • 计数器算法: 简单计数限流

1.3 限流应用场景

  • API限流: 控制API接口的访问频率
  • 数据库限流: 限制数据库访问频率
  • 外部服务限流: 控制调用外部服务的频率
  • 消息队列限流: 控制消息处理速度
  • 资源访问限流: 限制共享资源的访问

2. RateLimiter基础实现

2.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
/**
* 基础限流服务
* @author 运维实战
*/
@Service
public class BasicRateLimitService {

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

/**
* 创建限流器
* @param permitsPerSecond 每秒允许的请求数
* @return 限流器
*/
public RateLimiter createRateLimiter(double permitsPerSecond) {
logger.info("创建限流器,每秒允许请求数: {}", permitsPerSecond);
return RateLimiter.create(permitsPerSecond);
}

/**
* 创建预热限流器
* @param permitsPerSecond 每秒允许的请求数
* @param warmupPeriod 预热时间(秒)
* @return 限流器
*/
public RateLimiter createWarmupRateLimiter(double permitsPerSecond, long warmupPeriod) {
logger.info("创建预热限流器,每秒允许请求数: {}, 预热时间: {}秒", permitsPerSecond, warmupPeriod);
return RateLimiter.create(permitsPerSecond, Duration.ofSeconds(warmupPeriod));
}

/**
* 尝试获取令牌
* @param rateLimiter 限流器
* @return 是否获取成功
*/
public boolean tryAcquire(RateLimiter rateLimiter) {
boolean acquired = rateLimiter.tryAcquire();
logger.debug("尝试获取令牌: {}", acquired);
return acquired;
}

/**
* 尝试获取指定数量的令牌
* @param rateLimiter 限流器
* @param permits 令牌数量
* @return 是否获取成功
*/
public boolean tryAcquire(RateLimiter rateLimiter, int permits) {
boolean acquired = rateLimiter.tryAcquire(permits);
logger.debug("尝试获取{}个令牌: {}", permits, acquired);
return acquired;
}

/**
* 尝试获取令牌(带超时)
* @param rateLimiter 限流器
* @param timeout 超时时间
* @param unit 时间单位
* @return 是否获取成功
*/
public boolean tryAcquire(RateLimiter rateLimiter, long timeout, TimeUnit unit) {
boolean acquired = rateLimiter.tryAcquire(timeout, unit);
logger.debug("尝试获取令牌(超时{}ms): {}", unit.toMillis(timeout), acquired);
return acquired;
}

/**
* 阻塞获取令牌
* @param rateLimiter 限流器
* @return 获取令牌的等待时间(秒)
*/
public double acquire(RateLimiter rateLimiter) {
double waitTime = rateLimiter.acquire();
logger.debug("阻塞获取令牌,等待时间: {}秒", waitTime);
return waitTime;
}

/**
* 阻塞获取指定数量的令牌
* @param rateLimiter 限流器
* @param permits 令牌数量
* @return 获取令牌的等待时间(秒)
*/
public double acquire(RateLimiter rateLimiter, int permits) {
double waitTime = rateLimiter.acquire(permits);
logger.debug("阻塞获取{}个令牌,等待时间: {}秒", permits, waitTime);
return waitTime;
}

/**
* 获取限流器状态
* @param rateLimiter 限流器
* @return 限流器状态
*/
public RateLimiterStatus getRateLimiterStatus(RateLimiter rateLimiter) {
RateLimiterStatus status = new RateLimiterStatus();
status.setRate(rateLimiter.getRate());
status.setAvailablePermits(rateLimiter.availablePermits());
status.setCurrentTime(System.currentTimeMillis());

logger.debug("限流器状态: 速率={}, 可用令牌数={}", status.getRate(), status.getAvailablePermits());
return status;
}
}

2.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
/**
* 限流器状态类
* @author 运维实战
*/
@Data
public class RateLimiterStatus {

private double rate;
private double availablePermits;
private long currentTime;

public RateLimiterStatus() {
this.currentTime = System.currentTimeMillis();
}

/**
* 获取令牌使用率
* @return 令牌使用率
*/
public double getTokenUsageRate() {
if (rate == 0) return 0.0;
return (rate - availablePermits) / rate * 100;
}

/**
* 是否接近限流
* @return 是否接近限流
*/
public boolean isNearLimit() {
return availablePermits < rate * 0.1; // 可用令牌数小于10%
}

/**
* 是否已限流
* @return 是否已限流
*/
public boolean isLimited() {
return availablePermits <= 0;
}
}

2.3 API限流服务

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
/**
* API限流服务
* @author 运维实战
*/
@Service
public class ApiRateLimitService {

private final Map<String, RateLimiter> rateLimiters = new ConcurrentHashMap<>();
private final Map<String, RateLimiterConfig> configs = new ConcurrentHashMap<>();

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

/**
* 初始化API限流器
* @param apiKey API标识
* @param config 限流配置
*/
public void initRateLimiter(String apiKey, RateLimiterConfig config) {
logger.info("初始化API限流器: {}, 配置: {}", apiKey, config);

RateLimiter rateLimiter;
if (config.isWarmup()) {
rateLimiter = RateLimiter.create(config.getPermitsPerSecond(),
Duration.ofSeconds(config.getWarmupPeriod()));
} else {
rateLimiter = RateLimiter.create(config.getPermitsPerSecond());
}

rateLimiters.put(apiKey, rateLimiter);
configs.put(apiKey, config);

logger.info("API限流器初始化完成: {}", apiKey);
}

/**
* 检查API限流
* @param apiKey API标识
* @return 限流结果
*/
public RateLimitResult checkRateLimit(String apiKey) {
RateLimiter rateLimiter = rateLimiters.get(apiKey);
if (rateLimiter == null) {
logger.warn("API限流器不存在: {}", apiKey);
return RateLimitResult.allowed();
}

RateLimiterConfig config = configs.get(apiKey);
boolean acquired = rateLimiter.tryAcquire();

RateLimitResult result = new RateLimitResult();
result.setApiKey(apiKey);
result.setAllowed(acquired);
result.setRate(rateLimiter.getRate());
result.setAvailablePermits(rateLimiter.availablePermits());
result.setTimestamp(System.currentTimeMillis());

if (acquired) {
logger.debug("API限流检查通过: {}", apiKey);
} else {
logger.warn("API限流检查失败: {}, 可用令牌数: {}", apiKey, rateLimiter.availablePermits());
result.setMessage("请求频率过高,请稍后重试");
}

return result;
}

/**
* 检查API限流(带令牌数量)
* @param apiKey API标识
* @param permits 令牌数量
* @return 限流结果
*/
public RateLimitResult checkRateLimit(String apiKey, int permits) {
RateLimiter rateLimiter = rateLimiters.get(apiKey);
if (rateLimiter == null) {
logger.warn("API限流器不存在: {}", apiKey);
return RateLimitResult.allowed();
}

boolean acquired = rateLimiter.tryAcquire(permits);

RateLimitResult result = new RateLimitResult();
result.setApiKey(apiKey);
result.setAllowed(acquired);
result.setPermits(permits);
result.setRate(rateLimiter.getRate());
result.setAvailablePermits(rateLimiter.availablePermits());
result.setTimestamp(System.currentTimeMillis());

if (acquired) {
logger.debug("API限流检查通过: {}, 令牌数: {}", apiKey, permits);
} else {
logger.warn("API限流检查失败: {}, 令牌数: {}, 可用令牌数: {}",
apiKey, permits, rateLimiter.availablePermits());
result.setMessage("请求频率过高,请稍后重试");
}

return result;
}

/**
* 阻塞获取API令牌
* @param apiKey API标识
* @return 等待时间(秒)
*/
public double acquireApiToken(String apiKey) {
RateLimiter rateLimiter = rateLimiters.get(apiKey);
if (rateLimiter == null) {
logger.warn("API限流器不存在: {}", apiKey);
return 0.0;
}

double waitTime = rateLimiter.acquire();
logger.debug("API令牌获取成功: {}, 等待时间: {}秒", apiKey, waitTime);
return waitTime;
}

/**
* 更新API限流配置
* @param apiKey API标识
* @param newConfig 新配置
*/
public void updateRateLimitConfig(String apiKey, RateLimiterConfig newConfig) {
logger.info("更新API限流配置: {}, 新配置: {}", apiKey, newConfig);

RateLimiter rateLimiter = rateLimiters.get(apiKey);
if (rateLimiter != null) {
rateLimiter.setRate(newConfig.getPermitsPerSecond());
configs.put(apiKey, newConfig);
logger.info("API限流配置更新完成: {}", apiKey);
} else {
logger.warn("API限流器不存在,无法更新配置: {}", apiKey);
}
}

/**
* 获取API限流状态
* @param apiKey API标识
* @return 限流状态
*/
public RateLimiterStatus getApiRateLimitStatus(String apiKey) {
RateLimiter rateLimiter = rateLimiters.get(apiKey);
if (rateLimiter == null) {
return null;
}

RateLimiterStatus status = new RateLimiterStatus();
status.setRate(rateLimiter.getRate());
status.setAvailablePermits(rateLimiter.availablePermits());
status.setCurrentTime(System.currentTimeMillis());

return status;
}

/**
* 获取所有API限流状态
* @return 所有API限流状态
*/
public Map<String, RateLimiterStatus> getAllApiRateLimitStatus() {
Map<String, RateLimiterStatus> statusMap = new HashMap<>();

for (String apiKey : rateLimiters.keySet()) {
RateLimiterStatus status = getApiRateLimitStatus(apiKey);
if (status != null) {
statusMap.put(apiKey, status);
}
}

return statusMap;
}

/**
* 移除API限流器
* @param apiKey API标识
*/
public void removeRateLimiter(String apiKey) {
logger.info("移除API限流器: {}", apiKey);
rateLimiters.remove(apiKey);
configs.remove(apiKey);
}
}

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
/**
* 限流配置类
* @author 运维实战
*/
@Data
public class RateLimiterConfig {

/**
* 每秒允许的请求数
*/
private double permitsPerSecond;

/**
* 是否启用预热
*/
private boolean warmup = false;

/**
* 预热时间(秒)
*/
private long warmupPeriod = 10;

/**
* 最大突发请求数
*/
private int maxBurst = 100;

/**
* 是否启用动态调整
*/
private boolean enableDynamicAdjustment = false;

/**
* 调整间隔(秒)
*/
private long adjustmentInterval = 60;

public RateLimiterConfig() {}

public RateLimiterConfig(double permitsPerSecond) {
this.permitsPerSecond = permitsPerSecond;
}

public RateLimiterConfig(double permitsPerSecond, boolean warmup, long warmupPeriod) {
this.permitsPerSecond = permitsPerSecond;
this.warmup = warmup;
this.warmupPeriod = warmupPeriod;
}
}

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
/**
* 限流结果类
* @author 运维实战
*/
@Data
public class RateLimitResult {

private String apiKey;
private boolean allowed;
private int permits = 1;
private double rate;
private double availablePermits;
private String message;
private long timestamp;

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

/**
* 创建允许结果
* @return 允许结果
*/
public static RateLimitResult allowed() {
RateLimitResult result = new RateLimitResult();
result.setAllowed(true);
return result;
}

/**
* 创建拒绝结果
* @param message 拒绝消息
* @return 拒绝结果
*/
public static RateLimitResult rejected(String message) {
RateLimitResult result = new RateLimitResult();
result.setAllowed(false);
result.setMessage(message);
return result;
}

/**
* 是否被限流
* @return 是否被限流
*/
public boolean isLimited() {
return !allowed;
}

/**
* 获取令牌使用率
* @return 令牌使用率
*/
public double getTokenUsageRate() {
if (rate == 0) return 0.0;
return (rate - availablePermits) / rate * 100;
}
}

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
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
/**
* 分布式限流服务
* @author 运维实战
*/
@Service
public class DistributedRateLimitService {

@Autowired
private RedisTemplate<String, Object> redisTemplate;

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

private static final String RATE_LIMIT_KEY_PREFIX = "rate_limit:";
private static final String RATE_LIMIT_CONFIG_KEY_PREFIX = "rate_limit_config:";

/**
* 分布式限流检查
* @param key 限流键
* @param config 限流配置
* @return 限流结果
*/
public RateLimitResult checkDistributedRateLimit(String key, RateLimiterConfig config) {
try {
String rateLimitKey = RATE_LIMIT_KEY_PREFIX + key;
String configKey = RATE_LIMIT_CONFIG_KEY_PREFIX + key;

// 存储配置
redisTemplate.opsForValue().set(configKey, config, Duration.ofHours(1));

// 使用Lua脚本实现原子性限流检查
String luaScript = buildRateLimitLuaScript();

List<Object> result = redisTemplate.execute(new DefaultRedisScript<>(luaScript, List.class),
Collections.singletonList(rateLimitKey),
config.getPermitsPerSecond(),
System.currentTimeMillis() / 1000,
config.getMaxBurst()
);

boolean allowed = (Boolean) result.get(0);
double availablePermits = (Double) result.get(1);

RateLimitResult rateLimitResult = new RateLimitResult();
rateLimitResult.setApiKey(key);
rateLimitResult.setAllowed(allowed);
rateLimitResult.setRate(config.getPermitsPerSecond());
rateLimitResult.setAvailablePermits(availablePermits);
rateLimitResult.setTimestamp(System.currentTimeMillis());

if (!allowed) {
rateLimitResult.setMessage("分布式限流:请求频率过高");
}

logger.debug("分布式限流检查: key={}, allowed={}, availablePermits={}",
key, allowed, availablePermits);

return rateLimitResult;

} catch (Exception e) {
logger.error("分布式限流检查失败: key={}", key, e);
return RateLimitResult.rejected("分布式限流检查失败");
}
}

/**
* 构建限流Lua脚本
* @return Lua脚本
*/
private String buildRateLimitLuaScript() {
return """
local key = KEYS[1]
local permitsPerSecond = tonumber(ARGV[1])
local currentTime = tonumber(ARGV[2])
local maxBurst = tonumber(ARGV[3])

local bucket = redis.call('HMGET', key, 'tokens', 'lastRefillTime')
local tokens = tonumber(bucket[1]) or maxBurst
local lastRefillTime = tonumber(bucket[2]) or currentTime

-- 计算时间差和需要补充的令牌数
local timePassed = currentTime - lastRefillTime
local tokensToAdd = timePassed * permitsPerSecond
tokens = math.min(tokens + tokensToAdd, maxBurst)

-- 检查是否有足够的令牌
if tokens >= 1 then
tokens = tokens - 1
redis.call('HMSET', key, 'tokens', tokens, 'lastRefillTime', currentTime)
redis.call('EXPIRE', key, 3600)
return {true, tokens}
else
redis.call('HMSET', key, 'tokens', tokens, 'lastRefillTime', currentTime)
redis.call('EXPIRE', key, 3600)
return {false, tokens}
end
""";
}

/**
* 获取分布式限流状态
* @param key 限流键
* @return 限流状态
*/
public RateLimiterStatus getDistributedRateLimitStatus(String key) {
try {
String rateLimitKey = RATE_LIMIT_KEY_PREFIX + key;
String configKey = RATE_LIMIT_CONFIG_KEY_PREFIX + key;

// 获取配置
RateLimiterConfig config = (RateLimiterConfig) redisTemplate.opsForValue().get(configKey);
if (config == null) {
return null;
}

// 获取当前状态
Map<Object, Object> bucket = redisTemplate.opsForHash().entries(rateLimitKey);
if (bucket.isEmpty()) {
RateLimiterStatus status = new RateLimiterStatus();
status.setRate(config.getPermitsPerSecond());
status.setAvailablePermits(config.getMaxBurst());
return status;
}

double tokens = Double.parseDouble(bucket.get("tokens").toString());
long lastRefillTime = Long.parseLong(bucket.get("lastRefillTime").toString());
long currentTime = System.currentTimeMillis() / 1000;

// 计算当前可用令牌数
double timePassed = currentTime - lastRefillTime;
double tokensToAdd = timePassed * config.getPermitsPerSecond();
double availablePermits = Math.min(tokens + tokensToAdd, config.getMaxBurst());

RateLimiterStatus status = new RateLimiterStatus();
status.setRate(config.getPermitsPerSecond());
status.setAvailablePermits(availablePermits);
status.setCurrentTime(System.currentTimeMillis());

return status;

} catch (Exception e) {
logger.error("获取分布式限流状态失败: key={}", key, e);
return null;
}
}

/**
* 清理分布式限流数据
* @param key 限流键
*/
public void cleanupDistributedRateLimit(String key) {
try {
String rateLimitKey = RATE_LIMIT_KEY_PREFIX + key;
String configKey = RATE_LIMIT_CONFIG_KEY_PREFIX + key;

redisTemplate.delete(rateLimitKey);
redisTemplate.delete(configKey);

logger.info("分布式限流数据清理完成: key={}", key);

} catch (Exception e) {
logger.error("清理分布式限流数据失败: key={}", key, e);
}
}
}

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
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
/**
* 限流监控服务
* @author 运维实战
*/
@Service
public class RateLimitMonitorService {

@Autowired
private ApiRateLimitService apiRateLimitService;

@Autowired
private DistributedRateLimitService distributedRateLimitService;

private final Map<String, RateLimitMetrics> metricsMap = new ConcurrentHashMap<>();

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

/**
* 记录限流指标
* @param key 限流键
* @param result 限流结果
*/
public void recordMetrics(String key, RateLimitResult result) {
RateLimitMetrics metrics = metricsMap.computeIfAbsent(key, k -> new RateLimitMetrics());

if (result.isAllowed()) {
metrics.incrementAllowed();
} else {
metrics.incrementRejected();
}

metrics.setLastUpdateTime(System.currentTimeMillis());

logger.debug("限流指标记录: key={}, allowed={}, totalAllowed={}, totalRejected={}",
key, result.isAllowed(), metrics.getTotalAllowed(), metrics.getTotalRejected());
}

/**
* 获取限流指标
* @param key 限流键
* @return 限流指标
*/
public RateLimitMetrics getMetrics(String key) {
return metricsMap.get(key);
}

/**
* 获取所有限流指标
* @return 所有限流指标
*/
public Map<String, RateLimitMetrics> getAllMetrics() {
return new HashMap<>(metricsMap);
}

/**
* 定期监控限流状态
*/
@Scheduled(fixedRate = 30000) // 每30秒监控一次
public void monitorRateLimitStatus() {
try {
Map<String, RateLimiterStatus> apiStatusMap = apiRateLimitService.getAllApiRateLimitStatus();

for (Map.Entry<String, RateLimiterStatus> entry : apiStatusMap.entrySet()) {
String key = entry.getKey();
RateLimiterStatus status = entry.getValue();

logger.info("限流状态监控: key={}, 速率={}, 可用令牌数={}, 使用率={}%",
key, status.getRate(), status.getAvailablePermits(),
String.format("%.2f", status.getTokenUsageRate()));

// 检查是否接近限流
if (status.isNearLimit()) {
logger.warn("限流警告: key={}, 可用令牌数较低: {}", key, status.getAvailablePermits());
}

// 检查是否已限流
if (status.isLimited()) {
logger.error("限流触发: key={}, 可用令牌数为0", key);
}
}

// 监控指标
for (Map.Entry<String, RateLimitMetrics> entry : metricsMap.entrySet()) {
String key = entry.getKey();
RateLimitMetrics metrics = entry.getValue();

if (metrics.getTotalRequests() > 0) {
double rejectionRate = metrics.getRejectionRate();
logger.info("限流指标监控: key={}, 总请求数={}, 拒绝率={}%",
key, metrics.getTotalRequests(), String.format("%.2f", rejectionRate));

if (rejectionRate > 10) { // 拒绝率超过10%
logger.warn("限流拒绝率过高: key={}, 拒绝率={}%", key, String.format("%.2f", rejectionRate));
}
}
}

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

/**
* 清理过期指标
*/
@Scheduled(fixedRate = 300000) // 每5分钟清理一次
public void cleanupExpiredMetrics() {
try {
long currentTime = System.currentTimeMillis();
long expireTime = 30 * 60 * 1000; // 30分钟过期

Iterator<Map.Entry<String, RateLimitMetrics>> iterator = metricsMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, RateLimitMetrics> entry = iterator.next();
RateLimitMetrics metrics = entry.getValue();

if (currentTime - metrics.getLastUpdateTime() > expireTime) {
iterator.remove();
logger.info("清理过期限流指标: key={}", entry.getKey());
}
}

} catch (Exception e) {
logger.error("清理过期指标失败", e);
}
}
}

3.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
/**
* 限流指标类
* @author 运维实战
*/
@Data
public class RateLimitMetrics {

private long totalAllowed = 0;
private long totalRejected = 0;
private long lastUpdateTime = System.currentTimeMillis();

/**
* 增加允许计数
*/
public void incrementAllowed() {
this.totalAllowed++;
this.lastUpdateTime = System.currentTimeMillis();
}

/**
* 增加拒绝计数
*/
public void incrementRejected() {
this.totalRejected++;
this.lastUpdateTime = System.currentTimeMillis();
}

/**
* 获取总请求数
* @return 总请求数
*/
public long getTotalRequests() {
return totalAllowed + totalRejected;
}

/**
* 获取拒绝率
* @return 拒绝率
*/
public double getRejectionRate() {
long totalRequests = getTotalRequests();
if (totalRequests == 0) return 0.0;
return (double) totalRejected / totalRequests * 100;
}

/**
* 获取通过率
* @return 通过率
*/
public double getAllowanceRate() {
long totalRequests = getTotalRequests();
if (totalRequests == 0) return 0.0;
return (double) totalAllowed / totalRequests * 100;
}

/**
* 重置指标
*/
public void reset() {
this.totalAllowed = 0;
this.totalRejected = 0;
this.lastUpdateTime = System.currentTimeMillis();
}
}

4. 限流控制器

4.1 限流REST控制器

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
/**
* 限流REST控制器
* @author 运维实战
*/
@RestController
@RequestMapping("/api/ratelimit")
public class RateLimitController {

@Autowired
private ApiRateLimitService apiRateLimitService;

@Autowired
private DistributedRateLimitService distributedRateLimitService;

@Autowired
private RateLimitMonitorService rateLimitMonitorService;

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

/**
* 初始化API限流器
* @param request 初始化请求
* @return 初始化结果
*/
@PostMapping("/init")
public ResponseEntity<Map<String, String>> initRateLimiter(@RequestBody RateLimitInitRequest request) {
try {
logger.info("初始化API限流器: {}", request.getApiKey());

apiRateLimitService.initRateLimiter(request.getApiKey(), request.getConfig());

Map<String, String> response = new HashMap<>();
response.put("status", "SUCCESS");
response.put("message", "API限流器初始化成功");
response.put("apiKey", request.getApiKey());

return ResponseEntity.ok(response);

} catch (Exception e) {
logger.error("初始化API限流器失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 检查API限流
* @param request 限流检查请求
* @return 限流结果
*/
@PostMapping("/check")
public ResponseEntity<RateLimitResult> checkRateLimit(@RequestBody RateLimitCheckRequest request) {
try {
logger.info("检查API限流: {}", request.getApiKey());

RateLimitResult result;
if (request.getPermits() != null && request.getPermits() > 1) {
result = apiRateLimitService.checkRateLimit(request.getApiKey(), request.getPermits());
} else {
result = apiRateLimitService.checkRateLimit(request.getApiKey());
}

// 记录指标
rateLimitMonitorService.recordMetrics(request.getApiKey(), result);

return ResponseEntity.ok(result);

} catch (Exception e) {
logger.error("检查API限流失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 分布式限流检查
* @param request 分布式限流检查请求
* @return 限流结果
*/
@PostMapping("/distributed/check")
public ResponseEntity<RateLimitResult> checkDistributedRateLimit(@RequestBody DistributedRateLimitRequest request) {
try {
logger.info("检查分布式限流: {}", request.getKey());

RateLimitResult result = distributedRateLimitService.checkDistributedRateLimit(
request.getKey(), request.getConfig());

// 记录指标
rateLimitMonitorService.recordMetrics(request.getKey(), result);

return ResponseEntity.ok(result);

} catch (Exception e) {
logger.error("检查分布式限流失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取限流状态
* @param apiKey API标识
* @return 限流状态
*/
@GetMapping("/status/{apiKey}")
public ResponseEntity<RateLimiterStatus> getRateLimitStatus(@PathVariable String apiKey) {
try {
RateLimiterStatus status = apiRateLimitService.getApiRateLimitStatus(apiKey);
if (status != null) {
return ResponseEntity.ok(status);
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
logger.error("获取限流状态失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取所有限流状态
* @return 所有限流状态
*/
@GetMapping("/status")
public ResponseEntity<Map<String, RateLimiterStatus>> getAllRateLimitStatus() {
try {
Map<String, RateLimiterStatus> statusMap = apiRateLimitService.getAllApiRateLimitStatus();
return ResponseEntity.ok(statusMap);
} catch (Exception e) {
logger.error("获取所有限流状态失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取限流指标
* @param key 限流键
* @return 限流指标
*/
@GetMapping("/metrics/{key}")
public ResponseEntity<RateLimitMetrics> getRateLimitMetrics(@PathVariable String key) {
try {
RateLimitMetrics metrics = rateLimitMonitorService.getMetrics(key);
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();
}
}

/**
* 获取所有限流指标
* @return 所有限流指标
*/
@GetMapping("/metrics")
public ResponseEntity<Map<String, RateLimitMetrics>> getAllRateLimitMetrics() {
try {
Map<String, RateLimitMetrics> metricsMap = rateLimitMonitorService.getAllMetrics();
return ResponseEntity.ok(metricsMap);
} catch (Exception e) {
logger.error("获取所有限流指标失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 更新限流配置
* @param request 更新请求
* @return 更新结果
*/
@PutMapping("/config")
public ResponseEntity<Map<String, String>> updateRateLimitConfig(@RequestBody RateLimitUpdateRequest request) {
try {
logger.info("更新限流配置: {}", request.getApiKey());

apiRateLimitService.updateRateLimitConfig(request.getApiKey(), request.getConfig());

Map<String, String> response = new HashMap<>();
response.put("status", "SUCCESS");
response.put("message", "限流配置更新成功");
response.put("apiKey", request.getApiKey());

return ResponseEntity.ok(response);

} catch (Exception e) {
logger.error("更新限流配置失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 移除限流器
* @param apiKey API标识
* @return 移除结果
*/
@DeleteMapping("/{apiKey}")
public ResponseEntity<Map<String, String>> removeRateLimiter(@PathVariable String apiKey) {
try {
logger.info("移除限流器: {}", apiKey);

apiRateLimitService.removeRateLimiter(apiKey);

Map<String, String> response = new HashMap<>();
response.put("status", "SUCCESS");
response.put("message", "限流器移除成功");
response.put("apiKey", apiKey);

return ResponseEntity.ok(response);

} catch (Exception e) {
logger.error("移除限流器失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}

4.2 请求类定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 限流初始化请求类
* @author 运维实战
*/
@Data
public class RateLimitInitRequest {

private String apiKey;
private RateLimiterConfig config;

public RateLimitInitRequest() {}

public RateLimitInitRequest(String apiKey, RateLimiterConfig config) {
this.apiKey = apiKey;
this.config = config;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 限流检查请求类
* @author 运维实战
*/
@Data
public class RateLimitCheckRequest {

private String apiKey;
private Integer permits;

public RateLimitCheckRequest() {}

public RateLimitCheckRequest(String apiKey) {
this.apiKey = apiKey;
}

public RateLimitCheckRequest(String apiKey, Integer permits) {
this.apiKey = apiKey;
this.permits = permits;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 分布式限流请求类
* @author 运维实战
*/
@Data
public class DistributedRateLimitRequest {

private String key;
private RateLimiterConfig config;

public DistributedRateLimitRequest() {}

public DistributedRateLimitRequest(String key, RateLimiterConfig config) {
this.key = key;
this.config = config;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 限流更新请求类
* @author 运维实战
*/
@Data
public class RateLimitUpdateRequest {

private String apiKey;
private RateLimiterConfig config;

public RateLimitUpdateRequest() {}

public RateLimitUpdateRequest(String apiKey, RateLimiterConfig config) {
this.apiKey = apiKey;
this.config = config;
}
}

5. 限流注解和AOP

5.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
/**
* 限流注解
* @author 运维实战
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimit {

/**
* 限流键
*/
String key() default "";

/**
* 每秒允许的请求数
*/
double permitsPerSecond() default 10.0;

/**
* 令牌数量
*/
int permits() default 1;

/**
* 超时时间(毫秒)
*/
long timeout() default 0;

/**
* 是否启用预热
*/
boolean warmup() default false;

/**
* 预热时间(秒)
*/
long warmupPeriod() default 10;

/**
* 限流失败时的消息
*/
String message() default "请求频率过高,请稍后重试";

/**
* 限流失败时的HTTP状态码
*/
int statusCode() default 429;
}

5.2 限流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
/**
* 限流AOP切面
* @author 运维实战
*/
@Aspect
@Component
public class RateLimitAspect {

@Autowired
private ApiRateLimitService apiRateLimitService;

@Autowired
private RateLimitMonitorService rateLimitMonitorService;

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

/**
* 限流切点
*/
@Pointcut("@annotation(rateLimit)")
public void rateLimitPointcut(RateLimit rateLimit) {}

/**
* 限流环绕通知
* @param joinPoint 连接点
* @param rateLimit 限流注解
* @return 执行结果
* @throws Throwable 异常
*/
@Around("rateLimitPointcut(rateLimit)")
public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
String key = generateKey(joinPoint, rateLimit);

try {
// 初始化限流器
RateLimiterConfig config = new RateLimiterConfig(
rateLimit.permitsPerSecond(),
rateLimit.warmup(),
rateLimit.warmupPeriod()
);

apiRateLimitService.initRateLimiter(key, config);

// 检查限流
RateLimitResult result;
if (rateLimit.timeout() > 0) {
// 带超时的限流检查
result = checkRateLimitWithTimeout(key, rateLimit);
} else {
// 普通限流检查
result = apiRateLimitService.checkRateLimit(key, rateLimit.permits());
}

// 记录指标
rateLimitMonitorService.recordMetrics(key, result);

if (result.isAllowed()) {
logger.debug("限流检查通过: key={}", key);
return joinPoint.proceed();
} else {
logger.warn("限流检查失败: key={}, message={}", key, result.getMessage());
throw new RateLimitException(rateLimit.message(), rateLimit.statusCode());
}

} catch (RateLimitException e) {
throw e;
} catch (Exception e) {
logger.error("限流处理异常: key={}", key, e);
throw new RateLimitException("限流处理异常", 500);
}
}

/**
* 带超时的限流检查
* @param key 限流键
* @param rateLimit 限流注解
* @return 限流结果
*/
private RateLimitResult checkRateLimitWithTimeout(String key, RateLimit rateLimit) {
try {
// 获取限流器
RateLimiterStatus status = apiRateLimitService.getApiRateLimitStatus(key);
if (status == null) {
return RateLimitResult.allowed();
}

// 尝试获取令牌
boolean acquired = apiRateLimitService.tryAcquire(key, rateLimit.permits());

RateLimitResult result = new RateLimitResult();
result.setApiKey(key);
result.setAllowed(acquired);
result.setPermits(rateLimit.permits());
result.setRate(status.getRate());
result.setAvailablePermits(status.getAvailablePermits());
result.setTimestamp(System.currentTimeMillis());

if (!acquired) {
result.setMessage(rateLimit.message());
}

return result;

} catch (Exception e) {
logger.error("带超时的限流检查失败: key={}", key, e);
return RateLimitResult.rejected("限流检查失败");
}
}

/**
* 生成限流键
* @param joinPoint 连接点
* @param rateLimit 限流注解
* @return 限流键
*/
private String generateKey(ProceedingJoinPoint joinPoint, RateLimit rateLimit) {
if (!rateLimit.key().isEmpty()) {
return rateLimit.key();
}

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

return className + "." + methodName;
}
}

5.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
/**
* 限流异常类
* @author 运维实战
*/
public class RateLimitException extends RuntimeException {

private final int statusCode;

public RateLimitException(String message) {
super(message);
this.statusCode = 429;
}

public RateLimitException(String message, int statusCode) {
super(message);
this.statusCode = statusCode;
}

public RateLimitException(String message, Throwable cause) {
super(message, cause);
this.statusCode = 429;
}

public RateLimitException(String message, Throwable cause, int statusCode) {
super(message, cause);
this.statusCode = statusCode;
}

public int getStatusCode() {
return statusCode;
}
}

5.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
/**
* 限流异常处理器
* @author 运维实战
*/
@ControllerAdvice
public class RateLimitExceptionHandler {

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

/**
* 处理限流异常
* @param e 限流异常
* @return 错误响应
*/
@ExceptionHandler(RateLimitException.class)
public ResponseEntity<Map<String, Object>> handleRateLimitException(RateLimitException e) {
logger.warn("限流异常: {}", e.getMessage());

Map<String, Object> response = new HashMap<>();
response.put("error", "RATE_LIMIT_EXCEEDED");
response.put("message", e.getMessage());
response.put("timestamp", System.currentTimeMillis());

return ResponseEntity.status(e.getStatusCode()).body(response);
}
}

6. 实际应用示例

6.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
/**
* 使用限流注解的服务
* @author 运维实战
*/
@Service
public class RateLimitExampleService {

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

/**
* 普通限流示例
* @param data 数据
* @return 处理结果
*/
@RateLimit(key = "example.normal", permitsPerSecond = 5.0, message = "普通限流:请求频率过高")
public String normalRateLimit(String data) {
logger.info("执行普通限流示例: {}", data);

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

return "处理完成: " + data;
}

/**
* 预热限流示例
* @param data 数据
* @return 处理结果
*/
@RateLimit(key = "example.warmup", permitsPerSecond = 10.0, warmup = true, warmupPeriod = 5)
public String warmupRateLimit(String data) {
logger.info("执行预热限流示例: {}", data);

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

return "预热处理完成: " + data;
}

/**
* 多令牌限流示例
* @param data 数据
* @return 处理结果
*/
@RateLimit(key = "example.multi", permitsPerSecond = 20.0, permits = 3, message = "多令牌限流:请求频率过高")
public String multiTokenRateLimit(String data) {
logger.info("执行多令牌限流示例: {}", data);

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

return "多令牌处理完成: " + data;
}

/**
* 带超时限流示例
* @param data 数据
* @return 处理结果
*/
@RateLimit(key = "example.timeout", permitsPerSecond = 15.0, timeout = 1000, message = "超时限流:请求频率过高")
public String timeoutRateLimit(String data) {
logger.info("执行超时限流示例: {}", data);

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

return "超时处理完成: " + data;
}
}

6.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
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
/**
* 限流测试控制器
* @author 运维实战
*/
@RestController
@RequestMapping("/api/ratelimit/test")
public class RateLimitTestController {

@Autowired
private RateLimitExampleService rateLimitExampleService;

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

/**
* 普通限流测试
* @param data 测试数据
* @return 测试结果
*/
@GetMapping("/normal")
public ResponseEntity<Map<String, String>> testNormalRateLimit(@RequestParam String data) {
try {
String result = rateLimitExampleService.normalRateLimit(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 (RateLimitException e) {
logger.warn("普通限流测试被限流: {}", e.getMessage());
return ResponseEntity.status(e.getStatusCode()).build();
} catch (Exception e) {
logger.error("普通限流测试失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 预热限流测试
* @param data 测试数据
* @return 测试结果
*/
@GetMapping("/warmup")
public ResponseEntity<Map<String, String>> testWarmupRateLimit(@RequestParam String data) {
try {
String result = rateLimitExampleService.warmupRateLimit(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 (RateLimitException e) {
logger.warn("预热限流测试被限流: {}", e.getMessage());
return ResponseEntity.status(e.getStatusCode()).build();
} catch (Exception e) {
logger.error("预热限流测试失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 多令牌限流测试
* @param data 测试数据
* @return 测试结果
*/
@GetMapping("/multi")
public ResponseEntity<Map<String, String>> testMultiTokenRateLimit(@RequestParam String data) {
try {
String result = rateLimitExampleService.multiTokenRateLimit(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 (RateLimitException e) {
logger.warn("多令牌限流测试被限流: {}", e.getMessage());
return ResponseEntity.status(e.getStatusCode()).build();
} catch (Exception e) {
logger.error("多令牌限流测试失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 超时限流测试
* @param data 测试数据
* @return 测试结果
*/
@GetMapping("/timeout")
public ResponseEntity<Map<String, String>> testTimeoutRateLimit(@RequestParam String data) {
try {
String result = rateLimitExampleService.timeoutRateLimit(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 (RateLimitException e) {
logger.warn("超时限流测试被限流: {}", e.getMessage());
return ResponseEntity.status(e.getStatusCode()).build();
} catch (Exception e) {
logger.error("超时限流测试失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}

7. 总结

7.1 RateLimiter最佳实践

  1. 合理设置限流参数: 根据业务需求和系统容量设置限流参数
  2. 选择合适的限流策略: 根据场景选择令牌桶、漏桶等算法
  3. 监控限流状态: 实时监控限流器状态和性能指标
  4. 动态调整参数: 根据负载情况动态调整限流参数
  5. 异常处理: 实现完善的异常处理和用户友好提示

7.2 性能优化建议

  • 预热机制: 使用预热机制平滑启动限流器
  • 分布式限流: 在分布式环境中使用Redis等实现分布式限流
  • 监控告警: 建立完善的监控和告警机制
  • 缓存优化: 合理使用缓存减少限流检查开销
  • 异步处理: 使用异步处理提升系统响应性能

7.3 运维管理要点

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

通过本文的Guava的RateLimiter Java实战指南,您可以掌握限流原理、实现方法、性能优化技巧以及在企业级应用中的最佳实践,构建高效、稳定的限流系统!