package com.sf.vertx.handle; import com.sf.vertx.constans.RedisKeyConfig; import com.sf.vertx.enums.GatewayError; import com.sf.vertx.exception.ServiceException; import com.sf.vertx.pojo.SacCurrentLimiting; import com.sf.vertx.utils.AppUtils; 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; /*** * 内存存储 * * @author xy * */ @Slf4j public class AppRateLimitHandlerImpl implements AppRateLimitHandler { @Override public void handle(RoutingContext rc) { log.info("Enter AppRateLimitHandlerImpl.handle()"); String appCode = AppUtils.getAppConfigFromRoutingContext(rc).getAppCode(); SacCurrentLimiting currentLimiting = AppConfigHandler.getGlobalAppCurrentLimitingConfig(appCode); 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); try { restrictedCall.run(); } catch (Throwable t) { //t.printStackTrace(); log.info("app ratelimit:{}", key); rc.fail(new ServiceException(GatewayError.REQUEST_URL_RESTRICTED_BY_FLOW, currentLimiting.getStrategy().getDefaultResponse())); } } else { rc.next(); } } }