下面列出了怎么用org.springframework.http.server.RequestPath的API类实例代码及写法,或者点击链接到github查看源代码。
private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal,
@Nullable InetSocketAddress remoteAddress, List<HttpMessageReader<?>> messageReaders,
@Nullable ServerWebExchange exchange) {
this.method = method;
this.uri = uri;
this.pathContainer = RequestPath.parse(uri, contextPath);
this.headers = headers;
this.cookies = cookies;
this.body = body;
this.attributes = attributes;
this.queryParams = queryParams;
this.pathVariables = pathVariables;
this.session = session;
this.principal = principal;
this.remoteAddress = remoteAddress;
this.messageReaders = messageReaders;
this.exchange = exchange;
}
private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal,
@Nullable InetSocketAddress remoteAddress, List<HttpMessageReader<?>> messageReaders,
@Nullable ServerWebExchange exchange) {
this.method = method;
this.uri = uri;
this.pathContainer = RequestPath.parse(uri, contextPath);
this.headers = headers;
this.cookies = cookies;
this.body = body;
this.attributes = attributes;
this.queryParams = queryParams;
this.pathVariables = pathVariables;
this.session = session;
this.principal = principal;
this.remoteAddress = remoteAddress;
this.messageReaders = messageReaders;
this.exchange = exchange;
}
private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal,
@Nullable InetSocketAddress remoteAddress, List<HttpMessageReader<?>> messageReaders,
@Nullable ServerWebExchange exchange) {
this.method = method;
this.uri = uri;
this.pathContainer = RequestPath.parse(uri, contextPath);
this.headers = headers;
this.cookies = cookies;
this.body = body;
this.attributes = attributes;
this.queryParams = queryParams;
this.pathVariables = pathVariables;
this.session = session;
this.principal = principal;
this.remoteAddress = remoteAddress;
this.messageReaders = messageReaders;
this.exchange = exchange;
}
private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal,
@Nullable InetSocketAddress remoteAddress, List<HttpMessageReader<?>> messageReaders,
@Nullable ServerWebExchange exchange) {
this.method = method;
this.uri = uri;
this.pathContainer = RequestPath.parse(uri, contextPath);
this.headers = headers;
this.cookies = cookies;
this.body = body;
this.attributes = attributes;
this.queryParams = queryParams;
this.pathVariables = pathVariables;
this.session = session;
this.principal = principal;
this.remoteAddress = remoteAddress;
this.messageReaders = messageReaders;
this.exchange = exchange;
}
/**
* 请求信息日志过滤器
*
* @param exchange ServerWebExchange
* @param chain GatewayFilterChain
* @return Mono
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
HttpMethod method = request.getMethod();
RequestPath path = request.getPath();
String source = getIp(headers);
if (source == null || source.isEmpty()) {
source = request.getRemoteAddress().getAddress().getHostAddress();
}
String requestId = Util.uuid();
String fingerprint = Util.md5(source + headers.getFirst("user-agent"));
LogDto log = new LogDto();
log.setRequestId(requestId);
log.setSource(source);
log.setMethod(method.name());
log.setUrl(path.value());
log.setHeaders(headers.toSingleValueMap());
request.mutate().header("requestId", requestId).build();
request.mutate().header("fingerprint", fingerprint).build();
// 读取请求参数
MultiValueMap<String, String> params = request.getQueryParams();
log.setParams(params.isEmpty() ? null : params.toSingleValueMap());
// 如请求方法为GET或Body为空或Body不是Json,则打印日志后结束
long length = headers.getContentLength();
MediaType contentType = headers.getContentType();
if (length <= 0 || !contentType.equalsTypeAndSubtype(MediaType.APPLICATION_JSON)) {
logger.info("请求参数: {}", log.toString());
return chain.filter(exchange);
}
return readBody(exchange, chain, log);
}
public BuiltServerHttpRequest(String id, String method, URI uri, HttpHeaders headers,
MultiValueMap<String, HttpCookie> cookies, Flux<DataBuffer> body) {
this.id = id;
this.method = method;
this.uri = uri;
this.path = RequestPath.parse(uri, null);
this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
this.cookies = unmodifiableCopy(cookies);
this.queryParams = parseQueryParams(uri);
this.body = body;
}
/**
* Look up the best-matching handler method for the current request.
* If multiple matches are found, the best match is selected.
* @param exchange the current exchange
* @return the best-matching handler method, or {@code null} if no match
* @see #handleMatch
* @see #handleNoMatch
*/
@Nullable
protected HandlerMethod lookupHandlerMethod(ServerWebExchange exchange) throws Exception {
List<Match> matches = new ArrayList<>();
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, exchange);
if (!matches.isEmpty()) {
Comparator<Match> comparator = new MatchComparator(getMappingComparator(exchange));
matches.sort(comparator);
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (logger.isTraceEnabled()) {
logger.trace(exchange.getLogPrefix() + matches.size() + " matching mappings: " + matches);
}
if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
RequestPath path = exchange.getRequest().getPath();
throw new IllegalStateException(
"Ambiguous handler methods mapped for '" + path + "': {" + m1 + ", " + m2 + "}");
}
}
handleMatch(bestMatch.mapping, bestMatch.handlerMethod, exchange);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), exchange);
}
}
public BuiltServerHttpRequest(String id, String method, URI uri, HttpHeaders headers,
MultiValueMap<String, HttpCookie> cookies, Flux<DataBuffer> body) {
this.id = id;
this.method = method;
this.uri = uri;
this.path = RequestPath.parse(uri, null);
this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
this.cookies = unmodifiableCopy(cookies);
this.queryParams = parseQueryParams(uri);
this.body = body;
}
/**
* Look up the best-matching handler method for the current request.
* If multiple matches are found, the best match is selected.
* @param exchange the current exchange
* @return the best-matching handler method, or {@code null} if no match
* @see #handleMatch
* @see #handleNoMatch
*/
@Nullable
protected HandlerMethod lookupHandlerMethod(ServerWebExchange exchange) throws Exception {
List<Match> matches = new ArrayList<>();
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, exchange);
if (!matches.isEmpty()) {
Comparator<Match> comparator = new MatchComparator(getMappingComparator(exchange));
matches.sort(comparator);
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (logger.isTraceEnabled()) {
logger.trace(exchange.getLogPrefix() + matches.size() + " matching mappings: " + matches);
}
if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
RequestPath path = exchange.getRequest().getPath();
throw new IllegalStateException(
"Ambiguous handler methods mapped for '" + path + "': {" + m1 + ", " + m2 + "}");
}
}
handleMatch(bestMatch.mapping, bestMatch.handlerMethod, exchange);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), exchange);
}
}
@Override
public RequestPath getPath() {
return this.path;
}
@Override
public RequestPath getPath() {
return getDelegate().getPath();
}
@Override
public RequestPath getPath() {
return this.path;
}
@Test
public void testParseParametersWithItems() {
// Mock a request.
ServerWebExchange exchange = mock(ServerWebExchange.class);
ServerHttpRequest request = mock(ServerHttpRequest.class);
when(exchange.getRequest()).thenReturn(request);
RequestPath requestPath = mock(RequestPath.class);
when(request.getPath()).thenReturn(requestPath);
// Prepare gateway rules.
Set<GatewayFlowRule> rules = new HashSet<>();
String routeId1 = "my_test_route_A";
String api1 = "my_test_route_B";
String headerName = "X-Sentinel-Flag";
String paramName = "p";
GatewayFlowRule routeRule1 = new GatewayFlowRule(routeId1)
.setCount(2)
.setIntervalSec(2)
.setBurst(2)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
);
GatewayFlowRule routeRule2 = new GatewayFlowRule(routeId1)
.setCount(10)
.setIntervalSec(1)
.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
.setMaxQueueingTimeoutMs(600)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
.setFieldName(headerName)
);
GatewayFlowRule routeRule3 = new GatewayFlowRule(routeId1)
.setCount(20)
.setIntervalSec(1)
.setBurst(5)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
.setFieldName(paramName)
);
GatewayFlowRule routeRule4 = new GatewayFlowRule(routeId1)
.setCount(120)
.setIntervalSec(10)
.setBurst(30)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST)
);
GatewayFlowRule apiRule1 = new GatewayFlowRule(api1)
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
.setCount(5)
.setIntervalSec(1)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
.setFieldName(paramName)
);
rules.add(routeRule1);
rules.add(routeRule2);
rules.add(routeRule3);
rules.add(routeRule4);
rules.add(apiRule1);
GatewayRuleManager.loadRules(rules);
String expectedHost = "hello.test.sentinel";
String expectedAddress = "66.77.88.99";
String expectedHeaderValue1 = "Sentinel";
String expectedUrlParamValue1 = "17";
mockClientHostAddress(request, expectedAddress);
Map<String, String> expectedHeaders = new HashMap<String, String>() {{
put(headerName, expectedHeaderValue1); put("Host", expectedHost);
}};
mockHeaders(request, expectedHeaders);
mockSingleUrlParam(request, paramName, expectedUrlParamValue1);
Object[] params = paramParser.parseParameterFor(routeId1, exchange, e -> e.getResourceMode() == 0);
assertThat(params.length).isEqualTo(4);
assertThat(params[routeRule1.getParamItem().getIndex()]).isEqualTo(expectedAddress);
assertThat(params[routeRule2.getParamItem().getIndex()]).isEqualTo(expectedHeaderValue1);
assertThat(params[routeRule3.getParamItem().getIndex()]).isEqualTo(expectedUrlParamValue1);
assertThat(params[routeRule4.getParamItem().getIndex()]).isEqualTo(expectedHost);
assertThat(paramParser.parseParameterFor(api1, exchange, e -> e.getResourceMode() == 0).length).isZero();
String expectedUrlParamValue2 = "fs";
mockSingleUrlParam(request, paramName, expectedUrlParamValue2);
params = paramParser.parseParameterFor(api1, exchange, e -> e.getResourceMode() == 1);
assertThat(params.length).isEqualTo(1);
assertThat(params[apiRule1.getParamItem().getIndex()]).isEqualTo(expectedUrlParamValue2);
}
@Test
public void testPickMatchingApiDefinitions() {
// Mock a request.
ServerWebExchange exchange = mock(ServerWebExchange.class);
ServerHttpRequest request = mock(ServerHttpRequest.class);
when(exchange.getRequest()).thenReturn(request);
RequestPath requestPath = mock(RequestPath.class);
when(request.getPath()).thenReturn(requestPath);
// Prepare API definitions.
Set<ApiDefinition> apiDefinitions = new HashSet<>();
String apiName1 = "some_customized_api";
ApiDefinition api1 = new ApiDefinition(apiName1)
.setPredicateItems(Collections.singleton(
new ApiPathPredicateItem().setPattern("/product/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX)
));
String apiName2 = "another_customized_api";
ApiDefinition api2 = new ApiDefinition(apiName2)
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem().setPattern("/something"));
add(new ApiPathPredicateItem().setPattern("/other/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
apiDefinitions.add(api1);
apiDefinitions.add(api2);
GatewayApiDefinitionManager.loadApiDefinitions(apiDefinitions);
SentinelGatewayFilter filter = new SentinelGatewayFilter();
when(requestPath.value()).thenReturn("/product/123");
Set<String> matchingApis = filter.pickMatchingApiDefinitions(exchange);
assertThat(matchingApis.size()).isEqualTo(1);
assertThat(matchingApis.contains(apiName1)).isTrue();
when(requestPath.value()).thenReturn("/products");
assertThat(filter.pickMatchingApiDefinitions(exchange).size()).isZero();
when(requestPath.value()).thenReturn("/something");
matchingApis = filter.pickMatchingApiDefinitions(exchange);
assertThat(matchingApis.size()).isEqualTo(1);
assertThat(matchingApis.contains(apiName2)).isTrue();
when(requestPath.value()).thenReturn("/other/foo/3");
matchingApis = filter.pickMatchingApiDefinitions(exchange);
assertThat(matchingApis.size()).isEqualTo(1);
assertThat(matchingApis.contains(apiName2)).isTrue();
}
@Override
public RequestPath getPath() {
return this.path;
}
@Override
public RequestPath getPath() {
return getDelegate().getPath();
}
@Override
public RequestPath getPath() {
return this.path;
}
@Test
public void testParseParametersWithItems() {
// Mock a request.
ServerWebExchange exchange = mock(ServerWebExchange.class);
ServerHttpRequest request = mock(ServerHttpRequest.class);
when(exchange.getRequest()).thenReturn(request);
RequestPath requestPath = mock(RequestPath.class);
when(request.getPath()).thenReturn(requestPath);
// Prepare gateway rules.
Set<GatewayFlowRule> rules = new HashSet<>();
String routeId1 = "my_test_route_A";
String api1 = "my_test_route_B";
String headerName = "X-Sentinel-Flag";
String paramName = "p";
GatewayFlowRule routeRule1 = new GatewayFlowRule(routeId1)
.setCount(2)
.setIntervalSec(2)
.setBurst(2)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
);
GatewayFlowRule routeRule2 = new GatewayFlowRule(routeId1)
.setCount(10)
.setIntervalSec(1)
.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
.setMaxQueueingTimeoutMs(600)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
.setFieldName(headerName)
);
GatewayFlowRule routeRule3 = new GatewayFlowRule(routeId1)
.setCount(20)
.setIntervalSec(1)
.setBurst(5)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
.setFieldName(paramName)
);
GatewayFlowRule routeRule4 = new GatewayFlowRule(routeId1)
.setCount(120)
.setIntervalSec(10)
.setBurst(30)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST)
);
GatewayFlowRule apiRule1 = new GatewayFlowRule(api1)
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
.setCount(5)
.setIntervalSec(1)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
.setFieldName(paramName)
);
rules.add(routeRule1);
rules.add(routeRule2);
rules.add(routeRule3);
rules.add(routeRule4);
rules.add(apiRule1);
GatewayRuleManager.loadRules(rules);
String expectedHost = "hello.test.sentinel";
String expectedAddress = "66.77.88.99";
String expectedHeaderValue1 = "Sentinel";
String expectedUrlParamValue1 = "17";
mockClientHostAddress(request, expectedAddress);
Map<String, String> expectedHeaders = new HashMap<String, String>() {{
put(headerName, expectedHeaderValue1); put("Host", expectedHost);
}};
mockHeaders(request, expectedHeaders);
mockSingleUrlParam(request, paramName, expectedUrlParamValue1);
Object[] params = paramParser.parseParameterFor(routeId1, exchange, e -> e.getResourceMode() == 0);
assertThat(params.length).isEqualTo(4);
assertThat(params[routeRule1.getParamItem().getIndex()]).isEqualTo(expectedAddress);
assertThat(params[routeRule2.getParamItem().getIndex()]).isEqualTo(expectedHeaderValue1);
assertThat(params[routeRule3.getParamItem().getIndex()]).isEqualTo(expectedUrlParamValue1);
assertThat(params[routeRule4.getParamItem().getIndex()]).isEqualTo(expectedHost);
assertThat(paramParser.parseParameterFor(api1, exchange, e -> e.getResourceMode() == 0).length).isZero();
String expectedUrlParamValue2 = "fs";
mockSingleUrlParam(request, paramName, expectedUrlParamValue2);
params = paramParser.parseParameterFor(api1, exchange, e -> e.getResourceMode() == 1);
assertThat(params.length).isEqualTo(1);
assertThat(params[apiRule1.getParamItem().getIndex()]).isEqualTo(expectedUrlParamValue2);
}
@Test
public void testPickMatchingApiDefinitions() {
// Mock a request.
ServerWebExchange exchange = mock(ServerWebExchange.class);
ServerHttpRequest request = mock(ServerHttpRequest.class);
when(exchange.getRequest()).thenReturn(request);
RequestPath requestPath = mock(RequestPath.class);
when(request.getPath()).thenReturn(requestPath);
// Prepare API definitions.
Set<ApiDefinition> apiDefinitions = new HashSet<>();
String apiName1 = "some_customized_api";
ApiDefinition api1 = new ApiDefinition(apiName1)
.setPredicateItems(Collections.singleton(
new ApiPathPredicateItem().setPattern("/product/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX)
));
String apiName2 = "another_customized_api";
ApiDefinition api2 = new ApiDefinition(apiName2)
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem().setPattern("/something"));
add(new ApiPathPredicateItem().setPattern("/other/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
apiDefinitions.add(api1);
apiDefinitions.add(api2);
GatewayApiDefinitionManager.loadApiDefinitions(apiDefinitions);
SentinelGatewayFilter filter = new SentinelGatewayFilter();
when(requestPath.value()).thenReturn("/product/123");
Set<String> matchingApis = filter.pickMatchingApiDefinitions(exchange);
assertThat(matchingApis.size()).isEqualTo(1);
assertThat(matchingApis.contains(apiName1)).isTrue();
when(requestPath.value()).thenReturn("/products");
assertThat(filter.pickMatchingApiDefinitions(exchange).size()).isZero();
when(requestPath.value()).thenReturn("/something");
matchingApis = filter.pickMatchingApiDefinitions(exchange);
assertThat(matchingApis.size()).isEqualTo(1);
assertThat(matchingApis.contains(apiName2)).isTrue();
when(requestPath.value()).thenReturn("/other/foo/3");
matchingApis = filter.pickMatchingApiDefinitions(exchange);
assertThat(matchingApis.size()).isEqualTo(1);
assertThat(matchingApis.contains(apiName2)).isTrue();
}
/**
* 获取请求路径
*
* @param request 请求
* @return 请求路径
*/
private static String getRequestPath(ServerHttpRequest request) {
RequestPath path = request.getPath();
return path.toString();
}
/**
* Returns a structured representation of the request path including the
* context path + path within application portions, path segments with
* encoded and decoded values, and path parameters.
*/
RequestPath getPath();
/**
* Constructor with the URI and headers for the request.
* @param uri the URI for the request
* @param contextPath the context path for the request
* @param headers the headers for the request
*/
public AbstractServerHttpRequest(URI uri, @Nullable String contextPath, HttpHeaders headers) {
this.uri = uri;
this.path = RequestPath.parse(uri, contextPath);
this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
}
/**
* Returns a structured representation of the request path including the
* context path + path within application portions, path segments with
* encoded and decoded values, and path parameters.
*/
RequestPath getPath();
/**
* Constructor with the URI and headers for the request.
* @param uri the URI for the request
* @param contextPath the context path for the request
* @param headers the headers for the request
*/
public AbstractServerHttpRequest(URI uri, @Nullable String contextPath, HttpHeaders headers) {
this.uri = uri;
this.path = RequestPath.parse(uri, contextPath);
this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
}