You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.4 KiB

package com.example.demo.config;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
/**
* 本地限流工具类(基于Guava Cache)
*/
public class RateLimitUtil {
// 缓存:key=限流标识(用户ID/IP),value=占位符(无实际意义)
private static final Cache<String, Object> RATE_LIMIT_CACHE = CacheBuilder.newBuilder()
.expireAfterWrite(3, TimeUnit.SECONDS) // 3秒后自动过期(时间窗口)
.maximumSize(5000) // 最大缓存容量(防止内存溢出,根据用户量调整)
.build();
/**
* 判断是否允许请求
* @param key 限流唯一标识(如用户ID、IP)
* @return true=允许请求,false=限流中
*/
public static boolean isAllowed(String key) {
// 1. 尝试从缓存获取key,存在则说明3秒内已请求过(限流)
if (RATE_LIMIT_CACHE.getIfPresent(key) != null) {
return false;
}
// 2. 缓存中不存在,存入缓存(占位符用new Object()即可)
RATE_LIMIT_CACHE.put(key, new Object());
return true;
}
/**
* 手动移除限流标识(如接口执行失败时,释放限流)
* @param key 限流唯一标识
*/
public static void removeKey(String key) {
RATE_LIMIT_CACHE.invalidate(key);
}
}