0
# Route Matching
1
2
Path matching utilities providing support for exact, Ant-style pattern, and regular expression-based path matching for flexible resource identification in Spring Cloud Gateway.
3
4
## Capabilities
5
6
### RouteMatchers
7
8
Static utility class providing predicate factories for different types of path matching strategies.
9
10
```java { .api }
11
/**
12
* Utility class providing predicate factories for route matching
13
* All methods return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for reactive filtering
14
*/
15
public final class RouteMatchers {
16
/**
17
* Creates predicate that matches all requests
18
* @return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> that always returns true
19
*/
20
public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> all();
21
22
/**
23
* Creates Ant-style path pattern matcher
24
* @param pathPattern - Ant-style pattern (e.g., "/users/**", "/api/*/details")
25
* @return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for Ant pattern matching
26
*/
27
public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> antPath(String pathPattern);
28
29
/**
30
* Creates exact path matcher
31
* @param path - Exact path to match
32
* @return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for exact path matching
33
*/
34
public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> exactPath(String path);
35
36
/**
37
* Creates regular expression path matcher
38
* @param pathPattern - Regular expression pattern
39
* @return com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for regex matching
40
*/
41
public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> regexPath(String pathPattern);
42
}
43
```
44
45
### AntRoutePathMatcher
46
47
Ant-style path pattern matcher implementation using Spring's AntPathMatcher.
48
49
```java { .api }
50
/**
51
* Ant-style path pattern matcher
52
* Implements com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for reactive filtering
53
*/
54
public class AntRoutePathMatcher implements com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> {
55
/**
56
* Constructor with Ant-style pattern
57
* @param pattern - Ant-style pattern string (must not be blank)
58
*/
59
public AntRoutePathMatcher(String pattern);
60
61
/**
62
* Tests if exchange path matches the Ant pattern
63
* @param exchange - Server web exchange to test
64
* @return boolean - true if path matches pattern
65
*/
66
public boolean test(ServerWebExchange exchange);
67
68
/**
69
* Gets the configured pattern
70
* @return String - Ant-style pattern
71
*/
72
public String getPattern();
73
}
74
```
75
76
### RegexRoutePathMatcher
77
78
Regular expression path pattern matcher for complex path matching scenarios.
79
80
```java { .api }
81
/**
82
* Regular expression path pattern matcher
83
* Implements com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> for reactive filtering
84
*/
85
public class RegexRoutePathMatcher implements com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> {
86
/**
87
* Constructor with regex pattern
88
* @param pattern - Regular expression pattern (must not be blank)
89
*/
90
public RegexRoutePathMatcher(String pattern);
91
92
/**
93
* Tests if exchange path matches the regex pattern
94
* @param exchange - Server web exchange to test
95
* @return boolean - true if path matches regex
96
*/
97
public boolean test(ServerWebExchange exchange);
98
99
/**
100
* Gets the configured pattern
101
* @return String - Regular expression pattern
102
*/
103
public String getPattern();
104
}
105
```
106
107
## Usage Patterns
108
109
### Basic Route Matching
110
111
```java
112
import com.alibaba.csp.sentinel.adapter.gateway.sc.route.RouteMatchers;
113
import com.alibaba.csp.sentinel.util.function.Predicate;
114
115
// Match all requests
116
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> matchAll = RouteMatchers.all();
117
118
// Exact path matching
119
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> healthCheck = RouteMatchers.exactPath("/health");
120
121
// Ant-style pattern matching
122
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> apiPaths = RouteMatchers.antPath("/api/**");
123
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> userPaths = RouteMatchers.antPath("/users/*/profile");
124
125
// Regex pattern matching
126
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> versionedApi = RouteMatchers.regexPath("/api/v[0-9]+/.*");
127
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> numericIds = RouteMatchers.regexPath("/users/[0-9]+");
128
```
129
130
### Custom Route Filtering
131
132
```java
133
@Component
134
public class CustomRouteFilter {
135
136
private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> adminRoutes = RouteMatchers.antPath("/admin/**");
137
private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> apiRoutes = RouteMatchers.regexPath("/api/v[1-3]/.*");
138
private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> publicRoutes = RouteMatchers.exactPath("/public");
139
140
public boolean isAdminRoute(ServerWebExchange exchange) {
141
return adminRoutes.test(exchange);
142
}
143
144
public boolean isSupportedApiVersion(ServerWebExchange exchange) {
145
return apiRoutes.test(exchange);
146
}
147
148
public boolean isPublicRoute(ServerWebExchange exchange) {
149
return publicRoutes.test(exchange);
150
}
151
152
public String categorizeRoute(ServerWebExchange exchange) {
153
if (isAdminRoute(exchange)) {
154
return "admin";
155
} else if (isSupportedApiVersion(exchange)) {
156
return "api";
157
} else if (isPublicRoute(exchange)) {
158
return "public";
159
} else {
160
return "other";
161
}
162
}
163
}
164
```
165
166
### Complex Matching Logic
167
168
```java
169
public class AdvancedRouteMatchers {
170
171
// Combine multiple matchers
172
public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> createCompositeUserMatcher() {
173
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> userProfile = RouteMatchers.antPath("/users/*/profile");
174
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> userSettings = RouteMatchers.antPath("/users/*/settings");
175
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> userApi = RouteMatchers.regexPath("/api/users/[0-9]+");
176
177
return exchange -> userProfile.test(exchange) ||
178
userSettings.test(exchange) ||
179
userApi.test(exchange);
180
}
181
182
// Exclude certain patterns
183
public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> createApiMatcherExcludingHealth() {
184
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> allApi = RouteMatchers.antPath("/api/**");
185
com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> healthApi = RouteMatchers.exactPath("/api/health");
186
187
return exchange -> allApi.test(exchange) && !healthApi.test(exchange);
188
}
189
190
// Version-specific matching
191
public static com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> createVersionMatcher(int minVersion, int maxVersion) {
192
String pattern = String.format("/api/v[%d-%d]/.*", minVersion, maxVersion);
193
return RouteMatchers.regexPath(pattern);
194
}
195
}
196
```
197
198
### Integration with Flow Control
199
200
```java
201
@Configuration
202
public class RouteBasedFlowControl {
203
204
@PostConstruct
205
public void configureRouteBasedRules() {
206
List<FlowRule> rules = new ArrayList<>();
207
208
// Different limits for different route patterns
209
210
// Admin routes - very restrictive
211
FlowRule adminRule = new FlowRule();
212
adminRule.setResource("admin-routes");
213
adminRule.setCount(5);
214
adminRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
215
rules.add(adminRule);
216
217
// API routes - moderate limits
218
FlowRule apiRule = new FlowRule();
219
apiRule.setResource("api-routes");
220
apiRule.setCount(100);
221
apiRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
222
rules.add(apiRule);
223
224
FlowRuleManager.loadRules(rules);
225
}
226
}
227
228
@Component
229
public class RouteBasedResourceExtractor {
230
231
private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> adminMatcher = RouteMatchers.antPath("/admin/**");
232
private final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> apiMatcher = RouteMatchers.antPath("/api/**");
233
234
public String extractResourceName(ServerWebExchange exchange) {
235
if (adminMatcher.test(exchange)) {
236
return "admin-routes";
237
} else if (apiMatcher.test(exchange)) {
238
return "api-routes";
239
} else {
240
return "default-routes";
241
}
242
}
243
}
244
```
245
246
## Pattern Matching Examples
247
248
### Ant-Style Patterns
249
250
```java
251
// Common Ant patterns and their meanings:
252
253
RouteMatchers.antPath("/users/*"); // Matches: /users/123, /users/john
254
// Not: /users/123/profile
255
256
RouteMatchers.antPath("/users/**"); // Matches: /users/123, /users/123/profile, /users/a/b/c
257
// Any path starting with /users/
258
259
RouteMatchers.antPath("/api/*/details"); // Matches: /api/users/details, /api/orders/details
260
// Not: /api/users/123/details
261
262
RouteMatchers.antPath("/*.json"); // Matches: /data.json, /config.json
263
// Not: /api/data.json
264
```
265
266
### Regular Expression Patterns
267
268
```java
269
// Common regex patterns:
270
271
RouteMatchers.regexPath("/users/[0-9]+"); // Matches: /users/123, /users/456
272
// Not: /users/john
273
274
RouteMatchers.regexPath("/api/v[1-3]/.*"); // Matches: /api/v1/users, /api/v2/orders
275
// Not: /api/v4/users
276
277
RouteMatchers.regexPath("/files/.*\\.(jpg|png)"); // Matches: /files/image.jpg, /files/pic.png
278
// Not: /files/doc.pdf
279
280
RouteMatchers.regexPath("/[a-z]+/[0-9]{3,}"); // Matches: /users/1234, /orders/567
281
// Not: /Users/123, /users/12
282
```
283
284
### Performance Considerations
285
286
```java
287
public class PerformanceOptimizedMatchers {
288
289
// Pre-compile expensive matchers
290
private static final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> ADMIN_MATCHER =
291
RouteMatchers.antPath("/admin/**");
292
293
private static final com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> API_MATCHER =
294
RouteMatchers.regexPath("/api/v[0-9]+/.*");
295
296
// Reuse instances instead of creating new ones
297
public boolean isAdminPath(ServerWebExchange exchange) {
298
return ADMIN_MATCHER.test(exchange);
299
}
300
301
public boolean isApiPath(ServerWebExchange exchange) {
302
return API_MATCHER.test(exchange);
303
}
304
305
// For frequently used patterns, consider caching results
306
private final Map<String, Boolean> matchCache = new ConcurrentHashMap<>();
307
308
public boolean isMatchCached(String path, com.alibaba.csp.sentinel.util.function.Predicate<ServerWebExchange> matcher, ServerWebExchange exchange) {
309
return matchCache.computeIfAbsent(path, k -> matcher.test(exchange));
310
}
311
}
312
```
313
314
## Error Handling
315
316
### Pattern Validation
317
- Ant patterns are validated using Spring's AntPathMatcher
318
- Regex patterns are compiled and validated at construction time
319
- Invalid patterns throw `IllegalArgumentException` during matcher creation
320
321
### Runtime Safety
322
- All matchers handle null exchanges gracefully
323
- Path extraction failures return false rather than throwing exceptions
324
- Pattern compilation errors are caught during initialization
325
326
### Common Issues
327
- **Regex Escaping**: Remember to escape special characters in regex patterns
328
- **Ant Pattern Specificity**: More specific patterns should be checked before general ones
329
- **Performance**: Complex regex patterns can impact performance; use Ant patterns when possible