Here are the examples of the java api org.springframework.http.HttpStatus.TOO_MANY_REQUESTS taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
54 Examples
19
View Source File : CustomBlockRequestHandler.java
License : Apache License 2.0
Project Creator : evasnowind
License : Apache License 2.0
Project Creator : evasnowind
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
return // 状态码
ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS).contentType(// 内容类型为 text/plain 纯文本
MediaType.TEXT_PLAIN).bodyValue(// 错误提示
DEFAULT_BLOCK_MSG_PREFIX + ex.getClreplaced().getSimpleName());
}
19
View Source File : DefaultBlockRequestHandler.java
License : Apache License 2.0
Project Creator : eacdy
License : Apache License 2.0
Project Creator : eacdy
private Mono<ServerResponse> htmlErrorResponse(Throwable ex) {
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS).contentType(MediaType.TEXT_PLAIN).syncBody(DEFAULT_BLOCK_MSG_PREFIX + ex.getClreplaced().getSimpleName());
}
19
View Source File : SentinelFallbackHandler.java
License : Apache License 2.0
Project Creator : dromara
License : Apache License 2.0
Project Creator : dromara
@Override
public Mono<Void> generateError(final ServerWebExchange exchange, final Throwable throwable) {
Object error;
if (throwable instanceof DegradeException) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
error = SoulResultWrap.error(SoulResultEnum.SERVICE_RESULT_ERROR.getCode(), SoulResultEnum.SERVICE_RESULT_ERROR.getMsg(), null);
} else if (throwable instanceof FlowException) {
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
error = SoulResultWrap.error(SoulResultEnum.TOO_MANY_REQUESTS.getCode(), SoulResultEnum.TOO_MANY_REQUESTS.getMsg(), null);
} else if (throwable instanceof BlockException) {
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
error = SoulResultWrap.error(SoulResultEnum.SENTINEL_BLOCK_ERROR.getCode(), SoulResultEnum.SENTINEL_BLOCK_ERROR.getMsg(), null);
} else {
return Mono.error(throwable);
}
return WebFluxResultUtils.result(exchange, error);
}
19
View Source File : PIIS429ErrorMapper.java
License : Apache License 2.0
Project Creator : adorsys
License : Apache License 2.0
Project Creator : adorsys
@Override
public HttpStatus getErrorStatus() {
return HttpStatus.TOO_MANY_REQUESTS;
}
18
View Source File : RequestRateLimiterGatewayFilterFactoryTests.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Test
public void notAllowedWorks() {
replacedertFilterFactory(resolver2, "notallowedkey", false, HttpStatus.TOO_MANY_REQUESTS);
}
18
View Source File : DefaultBlockRequestHandler.java
License : Apache License 2.0
Project Creator : eacdy
License : Apache License 2.0
Project Creator : eacdy
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
if (acceptsHtml(exchange)) {
return htmlErrorResponse(ex);
}
// JSON result by default.
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS).contentType(MediaType.APPLICATION_JSON_UTF8).body(fromObject(buildErrorResult(ex)));
}
17
View Source File : OrderRateLimiterFilter.java
License : Apache License 2.0
Project Creator : luyunfeng
License : Apache License 2.0
Project Creator : luyunfeng
@Override
public Object run() throws ZuulException {
RequestContext requestContext = RequestContext.getCurrentContext();
if (!RATE_LIMITER.tryAcquire()) {
requestContext.setSendZuulResponse(false);
requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
}
return null;
}
17
View Source File : PIIS429ErrorMapperTest.java
License : Apache License 2.0
Project Creator : adorsys
License : Apache License 2.0
Project Creator : adorsys
@Test
void getErrorStatus_shouldReturn429() {
// When
HttpStatus errorStatus = piis429ErrorMapper.getErrorStatus();
// Then
replacedertEquals(HttpStatus.TOO_MANY_REQUESTS, errorStatus);
}
17
View Source File : AIS429ErrorMapperTest.java
License : Apache License 2.0
Project Creator : adorsys
License : Apache License 2.0
Project Creator : adorsys
@Test
void getErrorStatus_shouldReturn429() {
// When
HttpStatus errorStatus = ais429ErrorMapper.getErrorStatus();
// Then
replacedertEquals(HttpStatus.TOO_MANY_REQUESTS, errorStatus);
}
16
View Source File : LimiterExceptionAdvice.java
License : MIT License
Project Creator : zidoshare
License : MIT License
Project Creator : zidoshare
@ExceptionHandler(LimiterException.clreplaced)
@OriginalResponse
public ResponseEnreplacedy<Object> handleLimiterException(LimiterException e) {
return ResponseEnreplacedy.status(HttpStatus.TOO_MANY_REQUESTS).body(factory.error(CommonErrorCode.LIMIT, e.getMessage()));
}
16
View Source File : DemogatewayApplicationTests.java
License : Apache License 2.0
Project Creator : spring-cloud-samples
License : Apache License 2.0
Project Creator : spring-cloud-samples
@Test
public void rateLimiterWorks() {
WebTestClient authClient = client.mutate().filter(basicAuthentication("user", "preplacedword")).build();
boolean wasLimited = false;
for (int i = 0; i < 20; i++) {
FluxExchangeResult<Map> result = authClient.get().uri("/anything/1").header("Host", "www.limited.org").exchange().returnResult(Map.clreplaced);
if (result.getStatus().equals(HttpStatus.TOO_MANY_REQUESTS)) {
System.out.println("Received result: " + result);
wasLimited = true;
break;
}
}
replacedertThat(wasLimited).as("A HTTP 429 TOO_MANY_REQUESTS was not received").isTrue();
}
16
View Source File : ThrottleGatewayFilterFactory.java
License : MIT License
Project Creator : keets2012
License : MIT License
Project Creator : keets2012
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// TODO: get a token bucket for a key
log.debug("TokenBucket capacity: " + tokenBucket.getCapacity());
boolean consumed = tokenBucket.tryConsume();
if (consumed) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
}
16
View Source File : GlobalExceptionHandler.java
License : Apache License 2.0
Project Creator : febsteam
License : Apache License 2.0
Project Creator : febsteam
@ExceptionHandler(value = LimitAccessException.clreplaced)
public FebsResponse handleLimitAccessException(LimitAccessException e) {
log.error("LimitAccessException", e);
return new FebsResponse().code(HttpStatus.TOO_MANY_REQUESTS).message(e.getMessage());
}
15
View Source File : ResourceController.java
License : Apache License 2.0
Project Creator : tomsun28
License : Apache License 2.0
Project Creator : tomsun28
@DeleteMapping("/{resourceId}")
public ResponseEnreplacedy<Message> deleteResource(@PathVariable @NotBlank Long resourceId) {
if (resourceService.deleteResource(resourceId)) {
if (log.isDebugEnabled()) {
log.debug("delete resource success: {}", resourceId);
}
return ResponseEnreplacedy.ok().build();
} else {
Message message = Message.builder().errorMsg("delete resource fail, please try again later").build();
log.error("delete resource fail: {}", resourceId);
return ResponseEnreplacedy.status(HttpStatus.TOO_MANY_REQUESTS).body(message);
}
}
15
View Source File : GatewayRateLimitFilterByCpu.java
License : Apache License 2.0
Project Creator : SpringCloud
License : Apache License 2.0
Project Creator : SpringCloud
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获取网关所在机器的CPU使用情况
Double systemCpuUsage = metricsEndpoint.metric(METRIC_NAME, null).getMeasurements().stream().filter(Objects::nonNull).findFirst().map(MetricsEndpoint.Sample::getValue).filter(Double::isFinite).orElse(0.0D);
boolean isOpenRateLimit = systemCpuUsage > MAX_USAGE;
log.debug("system.cpu.usage: {}, isOpenRateLimit:{} ", systemCpuUsage, isOpenRateLimit);
if (isOpenRateLimit) {
// 当CPU的使用超过设置的最大阀值开启限流
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
} else {
return chain.filter(exchange);
}
}
15
View Source File : ThrottleGatewayFilter.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
TokenBucket tokenBucket = TokenBuckets.builder().withCapacity(capacity).withFixedIntervalRefillStrategy(refillTokens, refillPeriod, refillUnit).build();
// TODO: get a token bucket for a key
log.debug("TokenBucket capacity: " + tokenBucket.getCapacity());
boolean consumed = tokenBucket.tryConsume();
if (consumed) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
}
15
View Source File : RateFilter.java
License : GNU General Public License v2.0
Project Creator : singerdmx
License : GNU General Public License v2.0
Project Creator : singerdmx
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
if (AuthFilter.shouldBypreplaced(request.getRequestURI())) {
if (this.tokenBucket.isLimitExceeded(TokenBucketType.PUBLIC_ITEM)) {
LOGGER.error(request.getRequestURI() + " api limit exceeded");
// 429
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
return;
}
} else {
if (this.tokenBucket.isLimitExceeded(TokenBucketType.USER)) {
LOGGER.error("User requests limit exceeded");
// 429
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
return;
}
}
chain.doFilter(req, res);
}
15
View Source File : GlobalExceptionHandlerTest.java
License : Apache License 2.0
Project Creator : scalefocus
License : Apache License 2.0
Project Creator : scalefocus
@Test
public void testHandleRateLimitTimeoutException() {
RateLimitTimeoutException rateLimitTimeoutException = new RateLimitTimeoutException(TIMEOUT_SECONDS);
rateLimitTimeoutException.setStackTrace(buildDefaultStacktrace());
ResponseEnreplacedy<ErrorDTO> response = globalExceptionHandler.handleRateLimitTimeoutException(rateLimitTimeoutException);
replacedertAll(() -> replacedertEquals(HttpStatus.TOO_MANY_REQUESTS, response.getStatusCode()), () -> replacedertEquals(TIMEOUT_SECONDS.toString(), response.getBody().getMessage()));
}
15
View Source File : EarthquakeController.java
License : MIT License
Project Creator : ralscha
License : MIT License
Project Creator : ralscha
@GetMapping("/top1")
public ResponseEnreplacedy<Earthquake> getTop1() {
if (this.bucket.tryConsume(1)) {
Earthquake body = this.dsl.selectFrom(EARTHQUAKE).orderBy(EARTHQUAKE.MAG.desc()).limit(1).fetchOneInto(Earthquake.clreplaced);
return ResponseEnreplacedy.ok().body(body);
}
return ResponseEnreplacedy.status(HttpStatus.TOO_MANY_REQUESTS).build();
}
15
View Source File : SentinelWebFluxIntegrationTest.java
License : Apache License 2.0
Project Creator : eacdy
License : Apache License 2.0
Project Creator : eacdy
@Test
public void testCustomizedRequestOriginParser() throws Exception {
String url = "/hello";
String limitOrigin = "userA";
final String headerName = "S-User";
configureRulesFor(url, 0, limitOrigin);
WebFluxCallbackManager.setRequestOriginParser(exchange -> {
String origin = exchange.getRequest().getHeaders().getFirst(headerName);
return origin != null ? origin : "";
});
this.webClient.get().uri(url).accept(MediaType.TEXT_PLAIN).header(headerName, "userB").exchange().expectStatus().isOk().expectBody(String.clreplaced).isEqualTo(HELLO_STR);
// This will be blocked.
this.webClient.get().uri(url).accept(MediaType.TEXT_PLAIN).header(headerName, limitOrigin).exchange().expectStatus().isEqualTo(HttpStatus.TOO_MANY_REQUESTS).expectBody(String.clreplaced).value(StringContains.containsString(BLOCK_MSG_PREFIX));
this.webClient.get().uri(url).accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectBody(String.clreplaced).isEqualTo(HELLO_STR);
WebFluxCallbackManager.resetRequestOriginParser();
}
15
View Source File : VerificationPortalErrorControllerTest.java
License : Apache License 2.0
Project Creator : corona-warn-app
License : Apache License 2.0
Project Creator : corona-warn-app
@Test
@WithMockKeycloakAuth(name = "tester", value = "Role_Test")
public void handleErrorHandlesTooManyRequestsCorrectly() throws Exception {
log.info("process handleErrorHandlesTooManyRequestsCorrectly() RequestMethod.POST");
mockMvc.perform(post("/error").sessionAttr(TOKEN_ATTR_NAME, csrfToken).param(csrfToken.getParameterName(), csrfToken.getToken()).requestAttr(RequestDispatcher.ERROR_STATUS_CODE, HttpStatus.TOO_MANY_REQUESTS.value()).requestAttr(RequestDispatcher.ERROR_MESSAGE, "")).andExpect(status().isOk()).andExpect(view().name("error")).andExpect(model().attribute(ATTR_ERROR_MSG, equalTo(EXPECTED_ERROR_429_MESSAGE + rateLimitingSeconds + EXPECTED_SECONDS_MESSAGE)));
}
15
View Source File : VerificationPortalErrorControllerTest.java
License : Apache License 2.0
Project Creator : corona-warn-app
License : Apache License 2.0
Project Creator : corona-warn-app
@Test
@WithMockKeycloakAuth(name = "tester", value = "Role_Test")
public void handleErrorHandlesTooManyRequestsWithRateLimitCorrectly() throws Exception {
log.info("process handleErrorHandlesTooManyRequestsWithRateLimitCorrectly() RequestMethod.POST");
mockMvc.perform(post("/error").sessionAttr(TOKEN_ATTR_NAME, csrfToken).param(csrfToken.getParameterName(), csrfToken.getToken()).requestAttr(RequestDispatcher.ERROR_STATUS_CODE, HttpStatus.TOO_MANY_REQUESTS.value()).requestAttr(RequestDispatcher.ERROR_MESSAGE, SERVER_RATE_LIMIT_ERROR_REASON)).andExpect(status().isOk()).andExpect(view().name("error")).andExpect(model().attribute(ATTR_ERROR_MSG, equalTo(EXPECTED_ERROR_429_MESSAGE + EXPECTED_RATE_LIMIT_SERVER_TEXT_MESSAGE)));
}
15
View Source File : BladeBlockExceptionHandler.java
License : GNU Lesser General Public License v3.0
Project Creator : chillzhuang
License : GNU Lesser General Public License v3.0
Project Creator : chillzhuang
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
// Return 429 (Too Many Requests) by default.
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().print(JsonUtil.toJson(R.fail(e.getMessage())));
}
15
View Source File : RateLimitFilter.java
License : Apache License 2.0
Project Creator : CasterWx
License : Apache License 2.0
Project Creator : CasterWx
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if (AnnotationImport.rateLimiter.tryAcquire()) {
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else {
httpServletResponse.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
httpServletResponse.getWriter().write("too many request\n");
httpServletResponse.getWriter().flush();
return;
}
}
14
View Source File : RateLimitingFilter.java
License : Apache License 2.0
Project Creator : xebialabs
License : Apache License 2.0
Project Creator : xebialabs
/**
* Create a Zuul response error when the API limit is exceeded.
*/
private void apiLimitExceeded() {
RequestContext ctx = RequestContext.getCurrentContext();
ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
if (ctx.getResponseBody() == null) {
ctx.setResponseBody("API rate limit exceeded");
ctx.setSendZuulResponse(false);
}
}
14
View Source File : DefaultResponseEntityExceptionHandler.java
License : Apache License 2.0
Project Creator : TheBund1st
License : Apache License 2.0
Project Creator : TheBund1st
@ExceptionHandler(value = { TooManyRequestsException.clreplaced })
protected ResponseEnreplacedy<Object> handleTooManyRequests(TooManyRequestsException ex, WebRequest request) {
Map<String, Object> errorAttributes = getErrorAttributes(request);
errorAttributes.put("error", "1001");
errorAttributes.put("message", ex.getMessage());
return handleExceptionInternal(ex, errorAttributes, new HttpHeaders(), HttpStatus.TOO_MANY_REQUESTS, request);
}
14
View Source File : GlobalExceptionHandler.java
License : Apache License 2.0
Project Creator : scalefocus
License : Apache License 2.0
Project Creator : scalefocus
/**
* Reroute rate limit timeout exceptions to HTTP 429.
*
* @param rateLimitTimeoutException the caught exception
* @return ResponseEnreplacedy of HTTP Status 429, containing error details
*/
@ExceptionHandler({ RateLimitTimeoutException.clreplaced })
public final ResponseEnreplacedy<ErrorDTO> handleRateLimitTimeoutException(final RateLimitTimeoutException rateLimitTimeoutException) {
logException(rateLimitTimeoutException);
ErrorDTO errorDTO = ErrorDTO.fromExceptionBuilder().exception(rateLimitTimeoutException).build();
return ResponseEnreplacedy.status(HttpStatus.TOO_MANY_REQUESTS).body(errorDTO);
}
14
View Source File : RateLimitInterceptor.java
License : MIT License
Project Creator : ralscha
License : MIT License
Project Creator : ralscha
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ConsumptionProbe probe = this.bucket.tryConsumeAndReturnRemaining(this.numTokens);
if (probe.isConsumed()) {
response.addHeader("X-Rate-Limit-Remaining", Long.toString(probe.getRemainingTokens()));
return true;
}
// 429
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.addHeader("X-Rate-Limit-Retry-After-Milliseconds", Long.toString(TimeUnit.NANOSECONDS.toMillis(probe.getNanosToWaitForRefill())));
return false;
}
14
View Source File : Application.java
License : MIT License
Project Creator : ralscha
License : MIT License
Project Creator : ralscha
@GetMapping("/retry")
public ResponseEnreplacedy<String> retry() {
ConsumptionProbe probe = this.bucket.tryConsumeAndReturnRemaining(1);
if (probe.isConsumed()) {
return ResponseEnreplacedy.ok("OK");
}
return ResponseEnreplacedy.status(HttpStatus.TOO_MANY_REQUESTS).header(HttpHeaders.RETRY_AFTER, Long.toString(TimeUnit.NANOSECONDS.toSeconds(probe.getNanosToWaitForRefill()) + 1)).build();
}
14
View Source File : SentinelWebFluxIntegrationTest.java
License : Apache License 2.0
Project Creator : alibaba
License : Apache License 2.0
Project Creator : alibaba
@Test
public void testWebFluxRouterFunction() throws Exception {
String url = "/router/hello";
this.webClient.get().uri(url).accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectBody(String.clreplaced).isEqualTo(HELLO_STR);
ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
replacedertNotNull(cn);
replacedertEquals(1, cn.preplacedQps(), 0.01);
configureRulesFor(url, 0);
this.webClient.get().uri(url).accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isEqualTo(HttpStatus.TOO_MANY_REQUESTS).expectBody(String.clreplaced).value(StringContains.containsString(BLOCK_MSG_PREFIX));
}
13
View Source File : RateFilterTest.java
License : GNU General Public License v2.0
Project Creator : singerdmx
License : GNU General Public License v2.0
Project Creator : singerdmx
@Test
public void testRateFilter() throws Exception {
Group group = TestHelpers.createGroup(requestParams, USER, "testfilter");
Project p1 = TestHelpers.createProject(requestParams, USER, "p_Ledger_transaction", group, ProjectType.LEDGER);
// replacedumes this runs within the same minute as last request
ResponseEnreplacedy<Transaction> t1 = createTransaction(p1, "T1", "2019-12-01", "hero", 1000.0, 0);
replacedertEquals(HttpStatus.TOO_MANY_REQUESTS, t1.getStatusCode());
replacedertNull(t1.getBody());
// user locked for 5 minutes
t1 = createTransaction(p1, "T1", "2019-12-01", "hero", 1000.0, 0);
replacedertEquals(HttpStatus.UNAUTHORIZED, t1.getStatusCode());
t1 = createTransaction(p1, "T1", "2019-12-01", "hero", 1000.0, 0);
replacedertEquals(HttpStatus.UNAUTHORIZED, t1.getStatusCode());
}
13
View Source File : TravelsJavaAPIExceptionHandler.java
License : MIT License
Project Creator : mariazevedo88
License : MIT License
Project Creator : mariazevedo88
/**
* Method that handles with a HttpClientErrorException and returns a TooManyRequests error
* with status code = 429.
*
* @author Mariana Azevedo
* @since 01/04/2020
*
* @param exception
* @return ResponseEnreplacedy<Response<T>>
*/
@ExceptionHandler(value = { HttpClientErrorException.TooManyRequests.clreplaced })
protected ResponseEnreplacedy<Response<T>> handleTooManyRequestException(HttpClientErrorException exception) {
Response<T> response = new Response<>();
response.addErrorMsgToResponse(exception.getLocalizedMessage());
return ResponseEnreplacedy.status(HttpStatus.TOO_MANY_REQUESTS).body(response);
}
13
View Source File : RateLimiterPluginTest.java
License : Apache License 2.0
Project Creator : dromara
License : Apache License 2.0
Project Creator : dromara
/**
* rateLimiterPlugin doExecute , limiter not allowed case.
*/
@Test
public void doExecuteNotAllowedTest() {
doExecutePreInit();
when(redisRateLimiter.isAllowed(anyString(), any(RateLimiterHandle.clreplaced))).thenReturn(Mono.just(new RateLimiterResponse(false, 1)));
ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.clreplaced);
when(context.getBean(SoulResult.clreplaced)).thenReturn(new DefaultSoulResult());
SpringBeanUtils.getInstance().setCfgContext(context);
Mono<Void> result = rateLimiterPlugin.doExecute(exchange, chain, selectorData, ruleData);
StepVerifier.create(result).expectSubscription().verifyComplete();
replacedert.replacedertEquals(HttpStatus.TOO_MANY_REQUESTS, exchange.getResponse().getStatusCode());
}
13
View Source File : CommonFilterTest.java
License : Apache License 2.0
Project Creator : alibaba
License : Apache License 2.0
Project Creator : alibaba
private void testCommonBlockAndRedirectBlockPage(String url, ClusterNode cn) throws Exception {
configureRulesFor(url, 0);
// The request will be blocked and response is default block message.
WebServletConfig.setBlockPageHttpStatus(HttpStatus.OK.value());
this.mvc.perform(get(url).accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()).andExpect(content().string(FilterUtil.DEFAULT_BLOCK_MSG));
replacedertEquals(1, cn.blockQps(), 0.01);
WebServletConfig.setBlockPageHttpStatus(HttpStatus.TOO_MANY_REQUESTS.value());
this.mvc.perform(get(url).accept(MediaType.TEXT_PLAIN)).andExpect(status().isTooManyRequests()).andExpect(content().string(FilterUtil.DEFAULT_BLOCK_MSG));
// Test for redirect.
String redirectUrl = "http://some-location.com";
WebServletConfig.setBlockPage(redirectUrl);
this.mvc.perform(get(url).accept(MediaType.TEXT_PLAIN)).andExpect(status().is3xxRedirection()).andExpect(header().string("Location", redirectUrl + "?http_referer=http://localhost/hello"));
FlowRuleManager.loadRules(null);
WebServletConfig.setBlockPage("");
}
12
View Source File : EarthquakeController.java
License : MIT License
Project Creator : ralscha
License : MIT License
Project Creator : ralscha
@GetMapping("/top/{top}")
public ResponseEnreplacedy<List<Earthquake>> getTopOrderByMag(@PathVariable("top") int top) {
ConsumptionProbe probe = this.bucket.tryConsumeAndReturnRemaining(1);
if (probe.isConsumed()) {
List<Earthquake> body = this.dsl.selectFrom(EARTHQUAKE).orderBy(EARTHQUAKE.MAG.desc()).limit(top).fetchInto(Earthquake.clreplaced);
return ResponseEnreplacedy.ok().header("X-Rate-Limit-Remaining", Long.toString(probe.getRemainingTokens())).body(body);
}
// X-Rate-Limit-Retry-After-Seconds
return ResponseEnreplacedy.status(HttpStatus.TOO_MANY_REQUESTS).header("X-Rate-Limit-Retry-After-Milliseconds", Long.toString(TimeUnit.NANOSECONDS.toMillis(probe.getNanosToWaitForRefill()))).build();
}
12
View Source File : RateLimitByIpGatewayFilter.java
License : MIT License
Project Creator : keets2012
License : MIT License
Project Creator : keets2012
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
Bucket bucket = CACHE.computeIfAbsent(ip, k -> createNewBucket());
log.debug("IP: " + ip + ",TokenBucket Available Tokens: " + bucket.getAvailableTokens());
if (bucket.tryConsume(1)) {
return chain.filter(exchange);
} else {
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
}
}
11
View Source File : AlbedoUrlBlockHandler.java
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
License : GNU Lesser General Public License v3.0
Project Creator : somowhere
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
log.error("sentinel 降级 资源名称{}", e.getRule().getResource(), e);
response.setContentType(ContentType.JSON.toString());
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.getWriter().print(JSONUtil.toJsonStr(Result.buildFail(e.getMessage())));
}
11
View Source File : RateLimiterPlugin.java
License : Apache License 2.0
Project Creator : dromara
License : Apache License 2.0
Project Creator : dromara
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule) {
String handle = rule.getHandle();
RateLimiterHandle limiterHandle = GsonUtils.getInstance().fromJson(handle, RateLimiterHandle.clreplaced);
return redisRateLimiter.isAllowed(rule.getId(), limiterHandle).flatMap(response -> {
if (!response.isAllowed()) {
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
Object error = SoulResultWrap.error(SoulResultEnum.TOO_MANY_REQUESTS.getCode(), SoulResultEnum.TOO_MANY_REQUESTS.getMsg(), null);
return WebFluxResultUtils.result(exchange, error);
}
return chain.execute(exchange);
});
}
10
View Source File : GatewayRateLimitFilterByIp.java
License : Apache License 2.0
Project Creator : SpringCloud
License : Apache License 2.0
Project Creator : SpringCloud
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
Bucket bucket = LOCAL_CACHE.computeIfAbsent(ip, k -> createNewBucket());
log.debug("IP:{} ,令牌通可用的Token数量:{} ", ip, bucket.getAvailableTokens());
if (bucket.tryConsume(1)) {
return chain.filter(exchange);
} else {
// 当可用的令牌书为0是,进行限流返回429状态码
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
}
}
10
View Source File : PerClientRateLimitInterceptor.java
License : MIT License
Project Creator : ralscha
License : MIT License
Project Creator : ralscha
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Bucket requestBucket;
String apiKey = request.getHeader("X-api-key");
if (apiKey != null && !apiKey.isBlank()) {
if (apiKey.startsWith("1")) {
requestBucket = this.buckets.computeIfAbsent(apiKey, key -> premiumBucket());
} else {
requestBucket = this.buckets.computeIfAbsent(apiKey, key -> standardBucket());
}
} else {
requestBucket = this.freeBucket;
}
ConsumptionProbe probe = requestBucket.tryConsumeAndReturnRemaining(1);
if (probe.isConsumed()) {
response.addHeader("X-Rate-Limit-Remaining", Long.toString(probe.getRemainingTokens()));
return true;
}
// 429
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.addHeader("X-Rate-Limit-Retry-After-Milliseconds", Long.toString(TimeUnit.NANOSECONDS.toMillis(probe.getNanosToWaitForRefill())));
return false;
}
10
View Source File : PerClientHazelcastRateLimitInterceptor.java
License : MIT License
Project Creator : ralscha
License : MIT License
Project Creator : ralscha
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String apiKey = request.getHeader("X-api-key");
if (apiKey == null || apiKey.isBlank()) {
apiKey = "free";
}
Bucket requestBucket = this.buckets.getProxy(apiKey, getConfigSupplier(apiKey));
ConsumptionProbe probe = requestBucket.tryConsumeAndReturnRemaining(1);
if (probe.isConsumed()) {
response.addHeader("X-Rate-Limit-Remaining", Long.toString(probe.getRemainingTokens()));
return true;
}
// 429
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.addHeader("X-Rate-Limit-Retry-After-Milliseconds", Long.toString(TimeUnit.NANOSECONDS.toMillis(probe.getNanosToWaitForRefill())));
return false;
}
10
View Source File : PigUrlBlockHandler.java
License : Apache License 2.0
Project Creator : pig-mesh
License : Apache License 2.0
Project Creator : pig-mesh
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
log.error("sentinel 降级 资源名称{}", e.getRule().getResource(), e);
response.setContentType(ContentType.JSON.toString());
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.getWriter().print(JSONUtil.toJsonStr(R.failed(e.getMessage())));
}
9
View Source File : RouteEnhanceServiceImpl.java
License : Apache License 2.0
Project Creator : febsteam
License : Apache License 2.0
Project Creator : febsteam
private Mono<Void> doRateLimitCheck(AtomicBoolean limit, RateLimitRule rule, URI uri, String requestIp, String requestMethod, ServerHttpResponse response) {
boolean isRateLimitRuleHit = RateLimitRule.OPEN == Integer.parseInt(rule.getStatus()) && (RateLimitRule.METHOD_ALL.equalsIgnoreCase(rule.getRequestMethod()) || StringUtils.equalsIgnoreCase(requestMethod, rule.getRequestMethod()));
if (isRateLimitRuleHit) {
if (StringUtils.isNotBlank(rule.getLimitFrom()) && StringUtils.isNotBlank(rule.getLimitTo())) {
if (DateUtil.between(LocalTime.parse(rule.getLimitFrom()), LocalTime.parse(rule.getLimitTo()))) {
limit.set(true);
}
} else {
limit.set(true);
}
}
if (limit.get()) {
String requestUri = uri.getPath();
int count = routeEnhanceCacheService.getCurrentRequestCount(requestUri, requestIp);
if (count == 0) {
routeEnhanceCacheService.setCurrentRequestCount(requestUri, requestIp, Long.parseLong(rule.getIntervalSec()));
} else if (count >= Integer.parseInt(rule.getCount())) {
return FebsUtil.makeWebFluxResponse(response, MediaType.APPLICATION_JSON_VALUE, HttpStatus.TOO_MANY_REQUESTS, new FebsResponse().message("访问频率超限,请稍后再试"));
} else {
routeEnhanceCacheService.incrCurrentRequestCount(requestUri, requestIp);
}
}
return null;
}
8
View Source File : RateLimitInterceptor.java
License : MIT License
Project Creator : mariazevedo88
License : MIT License
Project Creator : mariazevedo88
/**
* @see HandlerInterceptor#preHandle(HttpServletRequest, HttpServletResponse, Object)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String apiKey = request.getHeader(TravelsApiUtil.HEADER_API_KEY);
if (apiKey == null || apiKey.isEmpty()) {
response.sendError(HttpStatus.BAD_REQUEST.value(), "Missing Header: " + TravelsApiUtil.HEADER_API_KEY);
log.error("Missing Header: " + TravelsApiUtil.HEADER_API_KEY);
return false;
}
Bucket tokenBucket = pricingPlanService.resolveBucket(apiKey);
ConsumptionProbe probe = tokenBucket.tryConsumeAndReturnRemaining(1);
if (probe.isConsumed()) {
response.addHeader(TravelsApiUtil.HEADER_LIMIT_REMAINING, String.valueOf(probe.getRemainingTokens()));
return true;
} else {
long waitForRefill = probe.getNanosToWaitForRefill() / 1_000_000_000;
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.addHeader(TravelsApiUtil.HEADER_RETRY_AFTER, String.valueOf(waitForRefill));
// 429
response.sendError(HttpStatus.TOO_MANY_REQUESTS.value(), "You have exhausted your API Request Quota");
log.info("You have exhausted your API Request Quota");
return false;
}
}
7
View Source File : RequestLimitFilter.java
License : Apache License 2.0
Project Creator : vakinge
License : Apache License 2.0
Project Creator : vakinge
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
try {
HttpServletRequest request = ctx.getRequest();
if (postOnly && !HttpMethod.POST.name().equalsIgnoreCase(request.getMethod())) {
return null;
}
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod()) || HttpMethod.HEAD.name().equalsIgnoreCase(request.getMethod())) {
return null;
}
if (gloabalLimiter != null) {
// limiter.acquire();
if (!gloabalLimiter.tryAcquire(1, TimeUnit.SECONDS)) {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
ctx.setResponseBody(MSG_TOO_MANY_REQUESTS);
return null;
}
}
// 后台系统不限制
if (perLimiter != null) {
UserSession session = SecurityDelegating.getCurrentSession();
if (!perLimiter.tryAcquire(request, session.getSessionId())) {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
ctx.setResponseBody(MSG_REQUEST_TOO_FAST);
return null;
}
}
} catch (Exception e) {
String error = "Error during filtering[RequestLimitFilter]";
log.error(error, e);
WebUtils.responseOutJson(ctx.getResponse(), JsonUtils.toJson(new WrapperResponse<>(500, error)));
}
return null;
}
7
View Source File : RattingInterceptorService.java
License : Apache License 2.0
Project Creator : getheimdall
License : Apache License 2.0
Project Creator : getheimdall
/**
* Limits the number of requests to a specific path
*
* @param name RLock name
* @param path rate limit key
*/
public void execute(String name, String path, Long calls, Interval interval, Long id) {
RequestContext ctx = RequestContext.getCurrentContext();
RLock lock = rateLimitRepository.getLock(name);
lock.lock();
RateLimit rate = rateLimitRepository.find(path);
if (rate == null) {
rate = rateLimitRepository.mountRatelimit(id, calls, interval);
}
if (rate.getLastRequest() == null) {
rate.setLastRequest(LocalDateTime.now());
}
if (hasIntervalEnded(rate)) {
rate.reset();
rate.decreaseRemaining();
rateLimitRepository.save(rate);
} else {
if (rate.hasRemaining()) {
rate.decreaseRemaining();
rateLimitRepository.save(rate);
} else {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
ctx.setResponseBody(HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
}
}
lock.unlock();
}
6
View Source File : LimiterControllerTest.java
License : MIT License
Project Creator : zidoshare
License : MIT License
Project Creator : zidoshare
@Test
public void testLimitPathVariableShouldWork() throws Exception {
String phone = "testLimitPathVariableShouldWork";
long startTime = System.currentTimeMillis();
mvc.perform(get("/limit/{phone}/sms", phone)).andExpect(status().isOk());
MvcResult mvcResult = mvc.perform(get("/limit/{phone}/sms", phone)).andReturn();
if (System.currentTimeMillis() - startTime < 5 * 1000) {
replacedertions.replacedertEquals(HttpStatus.TOO_MANY_REQUESTS.value(), mvcResult.getResponse().getStatus());
String content = mvcResult.getResponse().getContentreplacedtring(StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("rawtypes")
DefaultResult result = mapper.readValue(content, DefaultResult.clreplaced);
replacedertions.replacedertEquals(3, result.getCode(), "响应的code应当为频率被限制:" + CommonErrorCode.LIMIT);
Pattern pattern = Pattern.compile("^频率过高,请在 (\\d{1,2}) 秒后重试$");
Matcher matcher = pattern.matcher(result.getMessage());
replacedertions.replacedertTrue(matcher.matches(), "返回响应信息错误");
int lastTime = Integer.parseInt(matcher.group(1));
replacedertions.replacedertTrue(lastTime < 60, "剩余时间应小于60秒");
Thread.sleep(6 * 1000);
mvc.perform(get("/limit/{phone}/sms", phone)).andExpect(status().isOk());
mvc.perform(get("/limit/{phone}/sms", phone)).andExpect(status().is(HttpStatus.TOO_MANY_REQUESTS.value()));
} else {
replacedertions.fail("未能在60秒内完成请求,测试失败");
}
}
6
View Source File : LimiterControllerTest.java
License : MIT License
Project Creator : zidoshare
License : MIT License
Project Creator : zidoshare
@Test
public void testLimitShouldWorkOnMultipleCall() throws Exception {
long startTime = System.currentTimeMillis();
mvc.perform(get("/limit")).andExpect(status().isOk());
MvcResult mvcResult = mvc.perform(get("/limit")).andReturn();
if (System.currentTimeMillis() - startTime < 5 * 1000) {
replacedertions.replacedertEquals(HttpStatus.TOO_MANY_REQUESTS.value(), mvcResult.getResponse().getStatus());
String content = mvcResult.getResponse().getContentreplacedtring(StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("rawtypes")
DefaultResult result = mapper.readValue(content, DefaultResult.clreplaced);
replacedertions.replacedertEquals(3, result.getCode(), "响应的code应当为频率被限制:" + CommonErrorCode.LIMIT);
Pattern pattern = Pattern.compile("^频率过高,请在 (\\d{1,2}) 秒后重试$");
Matcher matcher = pattern.matcher(result.getMessage());
replacedertions.replacedertTrue(matcher.matches(), "返回响应信息错误");
int lastTime = Integer.parseInt(matcher.group(1));
replacedertions.replacedertTrue(lastTime < 60, "剩余时间应小于60秒");
Thread.sleep(6 * 1000);
mvc.perform(get("/limit")).andExpect(status().isOk());
mvc.perform(get("/limit")).andExpect(status().is(HttpStatus.TOO_MANY_REQUESTS.value()));
} else {
replacedertions.fail("未能在60秒内完成请求,测试失败");
}
}
6
View Source File : LimiterControllerTest.java
License : MIT License
Project Creator : zidoshare
License : MIT License
Project Creator : zidoshare
@Test
public void testLimitParamsShouldWork() throws Exception {
String phone = "testLimitParamsShouldWork";
long startTime = System.currentTimeMillis();
mvc.perform(get("/limit/sms").param("phone", phone)).andExpect(status().isOk());
MvcResult mvcResult = mvc.perform(get("/limit/sms").param("phone", phone)).andReturn();
if (System.currentTimeMillis() - startTime < 5 * 1000) {
replacedertions.replacedertEquals(HttpStatus.TOO_MANY_REQUESTS.value(), mvcResult.getResponse().getStatus());
String content = mvcResult.getResponse().getContentreplacedtring(StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("rawtypes")
DefaultResult result = mapper.readValue(content, DefaultResult.clreplaced);
replacedertions.replacedertEquals(3, result.getCode(), "响应的code应当为频率被限制:" + CommonErrorCode.LIMIT);
Pattern pattern = Pattern.compile("^频率过高,请在 (\\d{1,2}) 秒后重试$");
Matcher matcher = pattern.matcher(result.getMessage());
replacedertions.replacedertTrue(matcher.matches(), "返回响应信息错误");
int lastTime = Integer.parseInt(matcher.group(1));
replacedertions.replacedertTrue(lastTime < 60, "剩余时间应小于60秒");
Thread.sleep(6 * 1000);
mvc.perform(get("/limit/sms").param("phone", phone)).andExpect(status().isOk());
mvc.perform(get("/limit/sms").param("phone", phone)).andExpect(status().is(HttpStatus.TOO_MANY_REQUESTS.value()));
} else {
replacedertions.fail("未能在60秒内完成请求,测试失败");
}
}
5
View Source File : ZuulRateLimitFilter.java
License : Apache License 2.0
Project Creator : MarcGiffing
License : Apache License 2.0
Project Creator : MarcGiffing
@Override
public Object run() {
RequestContext context = getCurrentRequestContext();
HttpServletRequest request = context.getRequest();
Long remainingLimit = null;
for (RateLimitCheck<HttpServletRequest> rl : filterConfig.getRateLimitChecks()) {
ConsumptionProbeHolder probeHolder = rl.rateLimit(request, false);
if (probeHolder != null && probeHolder.getConsumptionProbe() != null) {
ConsumptionProbe probe = probeHolder.getConsumptionProbe();
if (probe.isConsumed()) {
remainingLimit = getRemainingLimit(remainingLimit, probe);
} else {
context.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
context.addZuulResponseHeader("X-Rate-Limit-Retry-After-Seconds", "" + TimeUnit.NANOSECONDS.toSeconds(probe.getNanosToWaitForRefill()));
context.setResponseBody(filterConfig.getHttpResponseBody());
context.setSendZuulResponse(false);
break;
}
if (filterConfig.getStrategy().equals(RateLimitConditionMatchingStrategy.FIRST)) {
break;
}
}
}
;
return null;
}
See More Examples