sac/sf-vertx/src/main/java/com/sf/vertx/handle/AppRateLimitHandlerImpl.java

44 lines
1.2 KiB
Java
Raw Normal View History

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) {
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;
}
}
}