| | |
| | | * 提示消息 支持国际化 格式为 {code} |
| | | */ |
| | | String message() default "{rate.limiter.message}"; |
| | | |
| | | /** |
| | | * 限流策略超时时间 默认一天(策略存活时间 会清除已存在的策略数据) |
| | | */ |
| | | int timeout() default 86400; |
| | | |
| | | } |
| | |
| | | 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, "}")) { |
| | |
| | | * @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 { |