2024-05-09 18:01:15 +08:00
|
|
|
package com.sf.vertx.handle;
|
|
|
|
|
|
|
|
import com.sf.vertx.constans.RedisKeyConfig;
|
|
|
|
import com.sf.vertx.pojo.SacCurrentLimiting;
|
|
|
|
|
|
|
|
import io.github.resilience4j.core.functions.CheckedRunnable;
|
|
|
|
import io.github.resilience4j.ratelimiter.RateLimiter;
|
|
|
|
import io.vertx.ext.web.RoutingContext;
|
|
|
|
import io.vertx.ext.web.handler.HttpException;
|
|
|
|
|
|
|
|
/***
|
|
|
|
* 内存存储
|
|
|
|
*
|
|
|
|
* @author xy
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public class AppRateLimitHandlerImpl implements AppRateLimitHandler {
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void handle(RoutingContext rc) {
|
2024-05-10 10:28:52 +08:00
|
|
|
String appCode = rc.request().headers().get(AppConfigHandler.getAppCodeHeaderKey());
|
|
|
|
SacCurrentLimiting currentLimiting = AppConfigHandler.getGlobalAppCurrentLimitingConfig(appCode);
|
2024-05-09 18:01:15 +08:00
|
|
|
|
|
|
|
if (currentLimiting != null) {
|
|
|
|
String key = RedisKeyConfig.APP_CURRENT_LIMITING_CONFIG_KEY + ":" + appCode;
|
|
|
|
RateLimiter rateLimiter = currentLimiting.getRegistry().rateLimiter(key);
|
|
|
|
CheckedRunnable restrictedCall = RateLimiter.decorateCheckedRunnable(rateLimiter, () -> {
|
|
|
|
rc.next();
|
|
|
|
return;
|
|
|
|
});
|
|
|
|
try {
|
|
|
|
restrictedCall.run();
|
|
|
|
} catch (Throwable t) {
|
|
|
|
t.printStackTrace();
|
|
|
|
rc.fail(new HttpException(10015, currentLimiting.getStrategy().getDefaultResponse()));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
rc.next();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|