基于org.redisson.api.RedissonClient client实现限流
RRateLimiter
redisson自带一个RRateLimiter
rate = 1L;//周期内准许流量
rateInterval = 1;//周期长度
rateIntervalUnit = SECONDS;//周期单位
RRateLimiter rateLimiter = client.getRateLimiter("key");
//设置速率
rateLimiter.trySetRate(RateType.OVERALL, rate, rateInterval , rateIntervalUnit );
// 设置一个过期时间避免长时间不用占用资源 可酌情使用
rateLimiter.expire( Duration.ofMillis(RateIntervalUnit.SECONDS.toMillis(rateInterval *2)));
//permits 需要消耗的资源数量一般为1
rateLimiter.acquire(permits);
# rateLimiter.acquire(permits);
# boolean tryAcquire(long permits, long timeout, TimeUnit unit);
这种用要求后续业务调用失败不能消耗次数没有相应api操作
RAtomicLong
原子计数器
RAtomicLong atomicValue = client.getAtomicLong("key"+timerange);
atomicValue.addAndGet(1) <= rate
//返还
//atomicValue.addAndGet(-1)
这种操作缺点非常明显不是滑动窗口需要预定义区间
ScoredSortedSet+批处理RBatch
为了做到可返还和滑动窗口使用ScoredSortedSet
RateLimiterResult limit(String key,long rate, long rateInterval, TimeUnit rateIntervalUnit)
//滑动窗口长度
long windwTime = rateIntervalUnit.toMillis(rateInterval);
//以当前时间为终点
long endTime = System.currentTimeMillis();
//区间起始点
long startTime = endTime- windwTime;
//唯一标记
String uuid = IdUtil.fastSimpleUUID();
//开始批处理
RBatch batch = client.createBatch();
//将当前标记和当前时间放集合
batch.getScoredSortedSet(key).addAsync(endTime, uuid);
//统计窗口范围的元素数量
Future<Integer> countFuture= batch.getScoredSortedSet(key).countAsync(startTime, true, endTime, true);
//清理超出窗口范围的元素
batch.getScoredSortedSet(key).removeRangeByScoreAsync(0, true, startTime, false);
//设置元素过期时间 可以可以放点余量 看个人
batch.getScoredSortedSet(key).expireAsync(Duration.ofMillis(windwTime));
//执行批处理 与服务端一次性交互完成
BatchResult<?> res = batch.execute();
int count = countFuture.get();
if(count<= rate){
//返回通过 并返回一个 Runnable 用于取消本次占用 当外部需要取消时调用
return RateLimiterResult .success(()->client.getScoredSortedSet(key).removeAsync(uuid));
}
# 当前已经超出了 根据自身需求 取消本次无效的消耗
client.getScoredSortedSet(key).removeAsync(uuid);
return RateLimiterResult .fail();
}
RevocableRateLimiter
基于上述情况可以自行实现
public interface RateLimiterResult {
/**是否通检测*/
boolean isPermit();
/**返还资源消耗*/
void revocation();
}
/**限定频率*/
interface Ratelimit {
int getRate();
long getRateInterval();
TimeUnit getRateIntervalUnit();
}
class RatelimitGroup {
String key;
boolean revocation;
List<Ratelimit> rules;
}
public interface RevocableRateLimiter {
/**同一个key多个频率
* 比如同一个用户1分钟n次,10分钟m次
*/
default RateLimiterResult permit(String key,List<Ratelimit> rules){
//转成下方的调用即可
return xxx;
}
/**多组规则
* 比如同一个用户/同一个ip/同一个机构
*/
RateLimiterResult permit( List<RatelimitGroup> groups);
}
RedisRevocableRateLimiter implements RevocableRateLimiter {
@Autowired
private RedissonClient client;
@Override
public RateLimiterResult permit(List<RatelimitGroup> groups) {
//参数检查
long endTime = System.currentTimeMillis();
final String uuid = IdUtil.fastSimpleUUID();
RBatch batch = client.createBatch();
//保持每个规则执行结果
List<Future<Boolean>> stageList = new ArrayList<>();
for (RatelimitGroup group : groups) {
String key = group.getKey();
List<Ratelimit> rules = group.getRules();
List<Future<Boolean>> stages = appendRules(batch, endTime, uuid, key, rules);
stageList.addAll(stages);
}
try {
batch.execute();//执行并等待结果
} catch (Exception e) {
//异常处理
return RateLimiterResult .fail();
}
boolean permit = isPermit(stageList);
if (!permit) {
revocation(groups, uuid);//或者放在回调中
return new RateLimiterResultImpl(permit, null);
}
return new RateLimiterResultImpl(permit, () -> revocation(groups, uuid));
}
// 添加同组的批处理行
protected List<Future<Boolean>> appendRules(RBatch batch, long endTime, String uuid, String key,
List<Ratelimit> rules) {
long maxWindwTime = 0;
List<Future<Boolean>> stages = new ArrayList<>();
batch.getScoredSortedSet(key).addAsync(endTime, uuid);
for (Ratelimit rule : rules) {
long windwTime = rule.rateIntervalMillis();
maxWindwTime = Math.max(maxWindwTime, windwTime);
Future<Boolean> stage = batch.getScoredSortedSet(key)
.countAsync(endTime - windwTime, true, endTime, true).thenApply(n -> isPermit(n, rule))
.toCompletableFuture()
;
stages.add(stage);
}
// 移除最长窗口之前的元素
batch.getScoredSortedSet(key).removeRangeByScoreAsync(0, true, endTime - maxWindwTime, false);
// 设置过期时间为最长窗口
batch.getScoredSortedSet(key).expireAsync(Duration.ofMillis(maxWindwTime));
return stages;
}
protected void revocation(List<RatelimitGroup> groups, String uuid) {
try {
RBatch batch = client.createBatch();
int n =0;
for (RatelimitGroup group : groups) {
String key = group.getKey();
if (group.isRevocation()) {
n++;
batch.getScoredSortedSet(key).removeAsync(uuid);
}
}
if(n>0) {
batch.executeAsync();
}
} catch (Exception e) {
//异常处理
}
}
protected boolean isPermit(List<Future<Boolean>> stageList) {
for (CompletableFuture<Boolean> stage : stageList) {
try {
Boolean v = stage.get();
if (!v.booleanValue()) {
return false;
}
} catch (InterruptedException | ExecutionException e) {
return false;
}
}
return true;
}
}
此处方式实现了多组多速率可返还的批量限制 如果需要一次消耗多个可以添加多个uuid即可,注意需要先加后撤不能先判定数量满足后再添加
使用
只需要再合适的地方比如Filter/Aspect读取规则并结合上下文生成key和速率表就可以批量判定