CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-alibaba-csp--sentinel-spring-cloud-gateway-adapter

Integration module providing flow control, traffic shaping, concurrency limiting, circuit breaking and system adaptive overload protection for Spring Cloud Gateway applications

Pending
Overview
Eval results
Files

block-handling.mddocs/

Block Request Handling

Customizable handlers for processing blocked requests, supporting JSON responses, HTML responses, and redirects with flexible callback management system.

Capabilities

BlockRequestHandler Interface

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

DefaultBlockRequestHandler

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: FlowException

RedirectBlockRequestHandler

Block 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);

GatewayCallbackManager

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

Usage Patterns

Custom JSON Response Handler

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());

Conditional Response Handler

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

Custom Origin Parser

// 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 Management

@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";
    }
}

Error Handling

Exception Safety

  • All handlers should handle exceptions gracefully to avoid disrupting the gateway
  • Return appropriate error responses even when custom logic fails
  • Use fallback responses for unexpected scenarios

Response Status Codes

  • 429 Too Many Requests: Standard for rate limiting (recommended)
  • 503 Service Unavailable: For system protection scenarios
  • 302 Found: For redirect responses
  • Custom status codes based on specific requirements

Content Type Handling

  • Respect client Accept headers when possible
  • Provide JSON responses for API clients
  • Provide HTML responses for browser clients
  • Support custom content types as needed

Install with Tessl CLI

npx tessl i tessl/maven-com-alibaba-csp--sentinel-spring-cloud-gateway-adapter

docs

api-management.md

block-handling.md

core-integration.md

index.md

request-processing.md

route-matching.md

tile.json