update 优化 限流注解增加固定清理时间
This commit is contained in:
parent
0baf2c5861
commit
8cd7e3c924
@ -38,4 +38,10 @@ public @interface RateLimiter {
|
||||
* 提示消息 支持国际化 格式为 {code}
|
||||
*/
|
||||
String message() default "{rate.limiter.message}";
|
||||
|
||||
/**
|
||||
* 限流策略超时时间 默认一天(策略存活时间 会清除已存在的策略数据)
|
||||
*/
|
||||
int timeout() default 86400;
|
||||
|
||||
}
|
||||
|
@ -54,13 +54,14 @@ public class RateLimiterAspect {
|
||||
public void doBefore(JoinPoint point, RateLimiter rateLimiter) {
|
||||
int time = rateLimiter.time();
|
||||
int count = rateLimiter.count();
|
||||
int timeout = rateLimiter.timeout();
|
||||
try {
|
||||
String combineKey = getCombineKey(rateLimiter, point);
|
||||
RateType rateType = RateType.OVERALL;
|
||||
if (rateLimiter.limitType() == LimitType.CLUSTER) {
|
||||
rateType = RateType.PER_CLIENT;
|
||||
}
|
||||
long number = RedisUtils.rateLimiter(combineKey, rateType, count, time);
|
||||
long number = RedisUtils.rateLimiter(combineKey, rateType, count, time, timeout);
|
||||
if (number == -1) {
|
||||
String message = rateLimiter.message();
|
||||
if (StringUtils.startsWith(message, "{") && StringUtils.endsWith(message, "}")) {
|
||||
|
@ -37,8 +37,22 @@ public class RedisUtils {
|
||||
* @return -1 表示失败
|
||||
*/
|
||||
public static long rateLimiter(String key, RateType rateType, int rate, int rateInterval) {
|
||||
return rateLimiter(key, rateType, rate, rateInterval, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 限流
|
||||
*
|
||||
* @param key 限流key
|
||||
* @param rateType 限流类型
|
||||
* @param rate 速率
|
||||
* @param rateInterval 速率间隔
|
||||
* @param timeout 超时时间
|
||||
* @return -1 表示失败
|
||||
*/
|
||||
public static long rateLimiter(String key, RateType rateType, int rate, int rateInterval, int timeout) {
|
||||
RRateLimiter rateLimiter = CLIENT.getRateLimiter(key);
|
||||
rateLimiter.trySetRate(rateType, rate, Duration.ofSeconds(rateInterval));
|
||||
rateLimiter.trySetRate(rateType, rate, Duration.ofSeconds(rateInterval), Duration.ofSeconds(timeout));
|
||||
if (rateLimiter.tryAcquire()) {
|
||||
return rateLimiter.availablePermits();
|
||||
} else {
|
||||
|
Loading…
x
Reference in New Issue
Block a user