漏斗限流
缺点:通过流量恒定 无法应对流量波动 如qps1000 , 800,1200 , 800 限流结果 800,1000, 800
令牌限流
每秒生产1000令牌 将上一秒剩余 令牌解决了流量波动 .需要限制令牌最大数 qps1000 800,1200,8000 结果 800,1200,800
package me.ele.marketing.budget.processor.helper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.util.concurrent.RateLimiter;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* 2021/7/2 1:10 下午
*/
public class Limiter {
private static Cache<String, RateLimiter> cache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(1, TimeUnit.MINUTES).build();
private static int default_limit = 5;
static {
default_limit = Integer.parseInt(System.getProperty("limit","5"));
}
public static boolean isLimit(String key) {
RateLimiter rateLimiter = null;
try {
rateLimiter = cache.get(key,()->{
return RateLimiter.create(default_limit);
});
} catch (ExecutionException e) {
//log
}
if (rateLimiter.tryAcquire(1000,TimeUnit.MILLISECONDS)) {
return false;
}
return true;
}
}