Integration module providing flow control, traffic shaping, concurrency limiting, circuit breaking and system adaptive overload protection for Spring Cloud Gateway applications
—
Customizable handlers for processing blocked requests, supporting JSON responses, HTML responses, and redirects with flexible callback management system.
Functional interface for handling blocked requests in reactive Spring Cloud Gateway environment.
/**
* Reactive handler for blocked requests
* Functional interface for custom block handling implementations
*/
@FunctionalInterface
public interface BlockRequestHandler {
/**
* Handle blocked request and return appropriate response
* @param exchange - Server web exchange for the blocked request
* @param t - Block exception that triggered the handling
* @return Mono<ServerResponse> representing the response to return
*/
Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t);
}Default implementation providing JSON and HTML error responses based on client Accept headers.
/**
* Default implementation of BlockRequestHandler
* Provides JSON responses by default, HTML for browser requests
*/
public class DefaultBlockRequestHandler implements BlockRequestHandler {
/**
* Default constructor
*/
public DefaultBlockRequestHandler();
/**
* Handles blocked requests with content negotiation
* Returns JSON response (429) by default, HTML for browsers
* Uses Accept header to determine response type
* @param exchange - Server web exchange
* @param ex - Block exception
* @return Mono<ServerResponse> with appropriate content type (JSON or HTML)
*/
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex);
}Response Examples:
JSON Response (default):
{
"code": 429,
"message": "Blocked by Sentinel: FlowException"
}HTML Response (for browsers):
Blocked by Sentinel: FlowExceptionBlock handler that redirects blocked requests to a specified URL.
/**
* Block handler that redirects blocked requests to specified URL
* Useful for redirecting blocked users to maintenance or error pages
*/
public class RedirectBlockRequestHandler implements BlockRequestHandler {
/**
* Constructor with redirect URL
* @param url - URL to redirect blocked requests to
*/
public RedirectBlockRequestHandler(String url);
/**
* Handles blocked requests by redirecting to configured URL
* @param exchange - Server web exchange
* @param t - Block exception
* @return Mono<ServerResponse> with temporary redirect (302)
*/
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t);
}Usage Examples:
// Redirect to maintenance page
BlockRequestHandler redirectHandler = new RedirectBlockRequestHandler("/maintenance.html");
GatewayCallbackManager.setBlockHandler(redirectHandler);
// Redirect to external error page
BlockRequestHandler externalRedirect = new RedirectBlockRequestHandler("https://example.com/blocked");
GatewayCallbackManager.setBlockHandler(externalRedirect);Static manager for configuring block request handlers and request origin parsers.
/**
* Manager for gateway callbacks including block handlers and origin parsers
* Provides static methods for configuration management
*/
public final class GatewayCallbackManager {
/**
* Gets current block request handler
* @return BlockRequestHandler current handler (never null)
*/
public static BlockRequestHandler getBlockHandler();
/**
* Sets custom block request handler
* @param blockHandler - Custom handler implementation (must not be null)
*/
public static void setBlockHandler(BlockRequestHandler blockHandler);
/**
* Resets block handler to default implementation
*/
public static void resetBlockHandler();
/**
* Gets current request origin parser function
* @return Function<ServerWebExchange, String> current parser (never null)
*/
public static Function<ServerWebExchange, String> getRequestOriginParser();
/**
* Sets custom request origin parser function
* @param requestOriginParser - Custom parser function (must not be null)
*/
public static void setRequestOriginParser(Function<ServerWebExchange, String> requestOriginParser);
/**
* Resets request origin parser to default implementation (returns empty string)
*/
public static void resetRequestOriginParser();
}public class CustomBlockRequestHandler implements BlockRequestHandler {
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
CustomErrorResponse error = new CustomErrorResponse(
"RATE_LIMIT_EXCEEDED",
"Too many requests. Please try again later.",
System.currentTimeMillis()
);
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
.contentType(MediaType.APPLICATION_JSON)
.body(fromObject(error));
}
private static class CustomErrorResponse {
private final String errorCode;
private final String message;
private final long timestamp;
// Constructor and getters...
}
}
// Configure custom handler
GatewayCallbackManager.setBlockHandler(new CustomBlockRequestHandler());public class ConditionalBlockRequestHandler implements BlockRequestHandler {
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
String path = exchange.getRequest().getPath().value();
if (path.startsWith("/api/")) {
// JSON response for API calls
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
.contentType(MediaType.APPLICATION_JSON)
.body(fromObject(Map.of("error", "Rate limit exceeded")));
} else {
// Redirect for web pages
return ServerResponse.temporaryRedirect(URI.create("/blocked.html")).build();
}
}
}// Extract origin from custom header
Function<ServerWebExchange, String> customOriginParser = exchange -> {
String customOrigin = exchange.getRequest().getHeaders().getFirst("X-Client-Origin");
if (customOrigin != null) {
return customOrigin;
}
// Fallback to IP address
InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
return remoteAddress != null ? remoteAddress.getAddress().getHostAddress() : "unknown";
};
GatewayCallbackManager.setRequestOriginParser(customOriginParser);@Configuration
public class SentinelGatewayConfiguration {
@PostConstruct
public void configureSentinel() {
// Set custom block handler
GatewayCallbackManager.setBlockHandler(new CustomBlockRequestHandler());
// Set custom origin parser
GatewayCallbackManager.setRequestOriginParser(exchange -> {
return extractClientId(exchange);
});
}
private String extractClientId(ServerWebExchange exchange) {
// Custom client identification logic
String apiKey = exchange.getRequest().getHeaders().getFirst("API-Key");
return apiKey != null ? apiKey : "anonymous";
}
}Install with Tessl CLI
npx tessl i tessl/maven-com-alibaba-csp--sentinel-spring-cloud-gateway-adapter