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

route-matching.mddocs/

Route Matching

Path matching utilities providing support for exact, Ant-style pattern, and regular expression-based path matching for flexible resource identification in Spring Cloud Gateway.

Capabilities

RouteMatchers

Static utility class providing predicate factories for different types of path matching strategies.

/**
 * Utility class providing predicate factories for route matching
 * All methods return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for reactive filtering
 */
public final class RouteMatchers {
    /**
     * Creates predicate that matches all requests
     * @return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> that always returns true
     */
    public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> all();
    
    /**
     * Creates Ant-style path pattern matcher
     * @param pathPattern - Ant-style pattern (e.g., "/users/**", "/api/*/details")
     * @return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for Ant pattern matching
     */
    public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> antPath(String pathPattern);
    
    /**
     * Creates exact path matcher
     * @param path - Exact path to match
     * @return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for exact path matching
     */
    public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> exactPath(String path);
    
    /**
     * Creates regular expression path matcher
     * @param pathPattern - Regular expression pattern
     * @return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for regex matching
     */
    public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> regexPath(String pathPattern);
}

AntRoutePathMatcher

Ant-style path pattern matcher implementation using Spring's AntPathMatcher.

/**
 * Ant-style path pattern matcher
 * Implements com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for reactive filtering
 */
public class AntRoutePathMatcher implements com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> {
    /**
     * Constructor with Ant-style pattern
     * @param pattern - Ant-style pattern string (must not be blank)
     */
    public AntRoutePathMatcher(String pattern);
    
    /**
     * Tests if exchange path matches the Ant pattern
     * @param exchange - Server web exchange to test
     * @return boolean - true if path matches pattern
     */
    public boolean test(ServerWebExchange exchange);
    
    /**
     * Gets the configured pattern
     * @return String - Ant-style pattern
     */
    public String getPattern();
}

RegexRoutePathMatcher

Regular expression path pattern matcher for complex path matching scenarios.

/**
 * Regular expression path pattern matcher
 * Implements com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for reactive filtering
 */
public class RegexRoutePathMatcher implements com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> {
    /**
     * Constructor with regex pattern
     * @param pattern - Regular expression pattern (must not be blank)
     */
    public RegexRoutePathMatcher(String pattern);
    
    /**
     * Tests if exchange path matches the regex pattern
     * @param exchange - Server web exchange to test
     * @return boolean - true if path matches regex
     */
    public boolean test(ServerWebExchange exchange);
    
    /**
     * Gets the configured pattern
     * @return String - Regular expression pattern
     */
    public String getPattern();
}

Usage Patterns

Basic Route Matching

import com.alibaba.csp.sentinel.adapter.gateway.sc.route.RouteMatchers;
import com.alibaba.csp.sentinel.util.function.Predicate;

// Match all requests
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> matchAll = RouteMatchers.all();

// Exact path matching
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> healthCheck = RouteMatchers.exactPath("/health");

// Ant-style pattern matching
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> apiPaths = RouteMatchers.antPath("/api/**");
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> userPaths = RouteMatchers.antPath("/users/*/profile");

// Regex pattern matching  
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> versionedApi = RouteMatchers.regexPath("/api/v[0-9]+/.*");
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> numericIds = RouteMatchers.regexPath("/users/[0-9]+");

Custom Route Filtering

@Component
public class CustomRouteFilter {
    
    private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> adminRoutes = RouteMatchers.antPath("/admin/**");
    private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> apiRoutes = RouteMatchers.regexPath("/api/v[1-3]/.*");
    private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> publicRoutes = RouteMatchers.exactPath("/public");
    
    public boolean isAdminRoute(ServerWebExchange exchange) {
        return adminRoutes.test(exchange);
    }
    
    public boolean isSupportedApiVersion(ServerWebExchange exchange) {
        return apiRoutes.test(exchange);
    }
    
    public boolean isPublicRoute(ServerWebExchange exchange) {
        return publicRoutes.test(exchange);
    }
    
    public String categorizeRoute(ServerWebExchange exchange) {
        if (isAdminRoute(exchange)) {
            return "admin";
        } else if (isSupportedApiVersion(exchange)) {
            return "api";
        } else if (isPublicRoute(exchange)) {
            return "public";
        } else {
            return "other";
        }
    }
}

Complex Matching Logic

public class AdvancedRouteMatchers {
    
    // Combine multiple matchers
    public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> createCompositeUserMatcher() {
        com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> userProfile = RouteMatchers.antPath("/users/*/profile");
        com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> userSettings = RouteMatchers.antPath("/users/*/settings");
        com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> userApi = RouteMatchers.regexPath("/api/users/[0-9]+");
        
        return exchange -> userProfile.test(exchange) || 
                          userSettings.test(exchange) || 
                          userApi.test(exchange);
    }
    
    // Exclude certain patterns
    public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> createApiMatcherExcludingHealth() {
        com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> allApi = RouteMatchers.antPath("/api/**");
        com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> healthApi = RouteMatchers.exactPath("/api/health");
        
        return exchange -> allApi.test(exchange) && !healthApi.test(exchange);
    }
    
    // Version-specific matching
    public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> createVersionMatcher(int minVersion, int maxVersion) {
        String pattern = String.format("/api/v[%d-%d]/.*", minVersion, maxVersion);
        return RouteMatchers.regexPath(pattern);
    }
}

Integration with Flow Control

@Configuration
public class RouteBasedFlowControl {
    
    @PostConstruct
    public void configureRouteBasedRules() {
        List<FlowRule> rules = new ArrayList<>();
        
        // Different limits for different route patterns
        
        // Admin routes - very restrictive
        FlowRule adminRule = new FlowRule();
        adminRule.setResource("admin-routes");
        adminRule.setCount(5);
        adminRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rules.add(adminRule);
        
        // API routes - moderate limits
        FlowRule apiRule = new FlowRule();
        apiRule.setResource("api-routes");
        apiRule.setCount(100);
        apiRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rules.add(apiRule);
        
        FlowRuleManager.loadRules(rules);
    }
}

@Component
public class RouteBasedResourceExtractor {
    
    private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> adminMatcher = RouteMatchers.antPath("/admin/**");
    private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> apiMatcher = RouteMatchers.antPath("/api/**");
    
    public String extractResourceName(ServerWebExchange exchange) {
        if (adminMatcher.test(exchange)) {
            return "admin-routes";
        } else if (apiMatcher.test(exchange)) {
            return "api-routes";
        } else {
            return "default-routes";
        }
    }
}

Pattern Matching Examples

Ant-Style Patterns

// Common Ant patterns and their meanings:

RouteMatchers.antPath("/users/*");        // Matches: /users/123, /users/john
                                         // Not: /users/123/profile

RouteMatchers.antPath("/users/**");       // Matches: /users/123, /users/123/profile, /users/a/b/c
                                         // Any path starting with /users/

RouteMatchers.antPath("/api/*/details");  // Matches: /api/users/details, /api/orders/details
                                         // Not: /api/users/123/details

RouteMatchers.antPath("/*.json");         // Matches: /data.json, /config.json
                                         // Not: /api/data.json

Regular Expression Patterns

// Common regex patterns:

RouteMatchers.regexPath("/users/[0-9]+");           // Matches: /users/123, /users/456
                                                   // Not: /users/john

RouteMatchers.regexPath("/api/v[1-3]/.*");         // Matches: /api/v1/users, /api/v2/orders
                                                   // Not: /api/v4/users

RouteMatchers.regexPath("/files/.*\\.(jpg|png)");  // Matches: /files/image.jpg, /files/pic.png
                                                   // Not: /files/doc.pdf

RouteMatchers.regexPath("/[a-z]+/[0-9]{3,}");      // Matches: /users/1234, /orders/567
                                                   // Not: /Users/123, /users/12

Performance Considerations

public class PerformanceOptimizedMatchers {
    
    // Pre-compile expensive matchers
    private static final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> ADMIN_MATCHER = 
        RouteMatchers.antPath("/admin/**");
    
    private static final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> API_MATCHER = 
        RouteMatchers.regexPath("/api/v[0-9]+/.*");
    
    // Reuse instances instead of creating new ones
    public boolean isAdminPath(ServerWebExchange exchange) {
        return ADMIN_MATCHER.test(exchange);
    }
    
    public boolean isApiPath(ServerWebExchange exchange) {
        return API_MATCHER.test(exchange);
    }
    
    // For frequently used patterns, consider caching results
    private final Map<String, Boolean> matchCache = new ConcurrentHashMap<>();
    
    public boolean isMatchCached(String path, com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> matcher, ServerWebExchange exchange) {
        return matchCache.computeIfAbsent(path, k -> matcher.test(exchange));
    }
}

Error Handling

Pattern Validation

  • Ant patterns are validated using Spring's AntPathMatcher
  • Regex patterns are compiled and validated at construction time
  • Invalid patterns throw IllegalArgumentException during matcher creation

Runtime Safety

  • All matchers handle null exchanges gracefully
  • Path extraction failures return false rather than throwing exceptions
  • Pattern compilation errors are caught during initialization

Common Issues

  • Regex Escaping: Remember to escape special characters in regex patterns
  • Ant Pattern Specificity: More specific patterns should be checked before general ones
  • Performance: Complex regex patterns can impact performance; use Ant patterns when possible

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