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

45 lines
1.4 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;
2024-05-24 18:54:30 +08:00
import com.sf.vertx.enums.GatewayError;
import com.sf.vertx.exception.ServiceException;
2024-05-09 18:01:15 +08:00
import com.sf.vertx.pojo.SacCurrentLimiting;
import com.sf.vertx.utils.AppUtils;
2024-05-09 18:01:15 +08:00
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;
import lombok.extern.slf4j.Slf4j;
2024-05-09 18:01:15 +08:00
/***
* 内存存储
*
* @author xy
*
*/
@Slf4j
2024-05-09 18:01:15 +08:00
public class AppRateLimitHandlerImpl implements AppRateLimitHandler {
@Override
public void handle(RoutingContext rc) {
2024-05-24 18:54:30 +08:00
log.info("Enter AppRateLimitHandlerImpl.handle()");
String appCode = AppUtils.getAppConfigFromRoutingContext(rc).getAppCode();
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);
2024-05-24 18:54:30 +08:00
CheckedRunnable restrictedCall = RateLimiter.decorateCheckedRunnable(rateLimiter, rc::next);
2024-05-09 18:01:15 +08:00
try {
restrictedCall.run();
} catch (Throwable t) {
//t.printStackTrace();
log.info("app ratelimit:{}", key);
2024-05-24 18:54:30 +08:00
rc.fail(new ServiceException(GatewayError.REQUEST_URL_RESTRICTED_BY_FLOW, currentLimiting.getStrategy().getDefaultResponse()));
2024-05-09 18:01:15 +08:00
}
} else {
rc.next();
}
}
}