init
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright 1999-2019 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import com.alibaba.csp.sentinel.EntryType;
|
||||
import com.alibaba.csp.sentinel.ResourceTypeConstants;
|
||||
import com.alibaba.csp.sentinel.adapter.reactor.ContextConfig;
|
||||
import com.alibaba.csp.sentinel.adapter.reactor.EntryConfig;
|
||||
import com.alibaba.csp.sentinel.adapter.reactor.SentinelReactorTransformer;
|
||||
import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.WebFluxCallbackManager;
|
||||
import com.alibaba.csp.sentinel.util.StringUtil;
|
||||
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.WebFilter;
|
||||
import org.springframework.web.server.WebFilterChain;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* @author Eric Zhao
|
||||
* @since 1.5.0
|
||||
*/
|
||||
public class SentinelWebFluxFilter implements WebFilter {
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
// Maybe we can get the URL pattern elsewhere via:
|
||||
// exchange.getAttributeOrDefault(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, path)
|
||||
String path = exchange.getRequest().getPath().value();
|
||||
|
||||
String finalPath = WebFluxCallbackManager.getUrlCleaner().apply(exchange, path);
|
||||
if (StringUtil.isEmpty(finalPath)) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
return chain.filter(exchange)
|
||||
.transform(buildSentinelTransformer(exchange, finalPath));
|
||||
}
|
||||
|
||||
private SentinelReactorTransformer<Void> buildSentinelTransformer(ServerWebExchange exchange, String finalPath) {
|
||||
String origin = Optional.ofNullable(WebFluxCallbackManager.getRequestOriginParser())
|
||||
.map(f -> f.apply(exchange))
|
||||
.orElse(EMPTY_ORIGIN);
|
||||
|
||||
return new SentinelReactorTransformer<>(new EntryConfig(finalPath, ResourceTypeConstants.COMMON_WEB,
|
||||
EntryType.IN, new ContextConfig(finalPath, origin)));
|
||||
}
|
||||
|
||||
private static final String EMPTY_ORIGIN = "";
|
||||
}
|
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 1999-2019 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux.callback;
|
||||
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* Reactive handler for the blocked request.
|
||||
*
|
||||
* @author Eric Zhao
|
||||
* @since 1.5.0
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface BlockRequestHandler {
|
||||
|
||||
/**
|
||||
* Handle the blocked request.
|
||||
*
|
||||
* @param exchange server exchange object
|
||||
* @param t block exception
|
||||
* @return server response to return
|
||||
*/
|
||||
Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t);
|
||||
}
|
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright 1999-2019 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux.callback;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.InvalidMediaTypeException;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
|
||||
/**
|
||||
* The default implementation of {@link BlockRequestHandler}.
|
||||
*
|
||||
* @author Eric Zhao
|
||||
* @since 1.5.0
|
||||
*/
|
||||
public class DefaultBlockRequestHandler implements BlockRequestHandler {
|
||||
|
||||
private static final String DEFAULT_BLOCK_MSG_PREFIX = "Blocked by Sentinel: ";
|
||||
|
||||
@Override
|
||||
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
|
||||
if (acceptsHtml(exchange)) {
|
||||
return htmlErrorResponse(ex);
|
||||
}
|
||||
// JSON result by default.
|
||||
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
|
||||
.contentType(MediaType.APPLICATION_JSON_UTF8)
|
||||
.body(fromObject(buildErrorResult(ex)));
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> htmlErrorResponse(Throwable ex) {
|
||||
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
|
||||
.contentType(MediaType.TEXT_PLAIN)
|
||||
.syncBody(DEFAULT_BLOCK_MSG_PREFIX + ex.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
private ErrorResult buildErrorResult(Throwable ex) {
|
||||
return new ErrorResult(HttpStatus.TOO_MANY_REQUESTS.value(),
|
||||
DEFAULT_BLOCK_MSG_PREFIX + ex.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reference from {@code DefaultErrorWebExceptionHandler} of Spring Boot.
|
||||
*/
|
||||
private boolean acceptsHtml(ServerWebExchange exchange) {
|
||||
try {
|
||||
List<MediaType> acceptedMediaTypes = exchange.getRequest().getHeaders().getAccept();
|
||||
acceptedMediaTypes.remove(MediaType.ALL);
|
||||
MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
|
||||
return acceptedMediaTypes.stream()
|
||||
.anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
|
||||
} catch (InvalidMediaTypeException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ErrorResult {
|
||||
private final int code;
|
||||
private final String message;
|
||||
|
||||
ErrorResult(int code, String message) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright 1999-2019 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux.callback;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
import com.alibaba.csp.sentinel.util.AssertUtil;
|
||||
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
* @author Eric Zhao
|
||||
* @since 1.5.0
|
||||
*/
|
||||
public final class WebFluxCallbackManager {
|
||||
|
||||
private static final BiFunction<ServerWebExchange, String, String> DEFAULT_URL_CLEANER = (w, url) -> url;
|
||||
private static final Function<ServerWebExchange, String> DEFAULT_ORIGIN_PARSER = (w) -> "";
|
||||
|
||||
/**
|
||||
* BlockRequestHandler: (serverExchange, exception) -> response
|
||||
*/
|
||||
private static volatile BlockRequestHandler blockHandler = new DefaultBlockRequestHandler();
|
||||
/**
|
||||
* UrlCleaner: (serverExchange, originalUrl) -> finalUrl
|
||||
*/
|
||||
private static volatile BiFunction<ServerWebExchange, String, String> urlCleaner = DEFAULT_URL_CLEANER;
|
||||
/**
|
||||
* RequestOriginParser: (serverExchange) -> origin
|
||||
*/
|
||||
private static volatile Function<ServerWebExchange, String> requestOriginParser = DEFAULT_ORIGIN_PARSER;
|
||||
|
||||
public static /*@NonNull*/ BlockRequestHandler getBlockHandler() {
|
||||
return blockHandler;
|
||||
}
|
||||
|
||||
public static void resetBlockHandler() {
|
||||
WebFluxCallbackManager.blockHandler = new DefaultBlockRequestHandler();
|
||||
}
|
||||
|
||||
public static void setBlockHandler(BlockRequestHandler blockHandler) {
|
||||
AssertUtil.notNull(blockHandler, "blockHandler cannot be null");
|
||||
WebFluxCallbackManager.blockHandler = blockHandler;
|
||||
}
|
||||
|
||||
public static /*@NonNull*/ BiFunction<ServerWebExchange, String, String> getUrlCleaner() {
|
||||
return urlCleaner;
|
||||
}
|
||||
|
||||
public static void resetUrlCleaner() {
|
||||
WebFluxCallbackManager.urlCleaner = DEFAULT_URL_CLEANER;
|
||||
}
|
||||
|
||||
public static void setUrlCleaner(BiFunction<ServerWebExchange, String, String> urlCleaner) {
|
||||
AssertUtil.notNull(urlCleaner, "urlCleaner cannot be null");
|
||||
WebFluxCallbackManager.urlCleaner = urlCleaner;
|
||||
}
|
||||
|
||||
public static /*@NonNull*/ Function<ServerWebExchange, String> getRequestOriginParser() {
|
||||
return requestOriginParser;
|
||||
}
|
||||
|
||||
public static void resetRequestOriginParser() {
|
||||
WebFluxCallbackManager.requestOriginParser = DEFAULT_ORIGIN_PARSER;
|
||||
}
|
||||
|
||||
public static void setRequestOriginParser(Function<ServerWebExchange, String> requestOriginParser) {
|
||||
AssertUtil.notNull(requestOriginParser, "requestOriginParser cannot be null");
|
||||
WebFluxCallbackManager.requestOriginParser = requestOriginParser;
|
||||
}
|
||||
|
||||
private WebFluxCallbackManager() {}
|
||||
}
|
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright 1999-2019 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux.exception;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.WebFluxCallbackManager;
|
||||
import com.alibaba.csp.sentinel.slots.block.BlockException;
|
||||
import com.alibaba.csp.sentinel.util.function.Supplier;
|
||||
|
||||
import org.springframework.http.codec.HttpMessageWriter;
|
||||
import org.springframework.http.codec.ServerCodecConfigurer;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.reactive.result.view.ViewResolver;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.WebExceptionHandler;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* @author Eric Zhao
|
||||
* @since 1.5.0
|
||||
*/
|
||||
public class SentinelBlockExceptionHandler implements WebExceptionHandler {
|
||||
|
||||
private List<ViewResolver> viewResolvers;
|
||||
private List<HttpMessageWriter<?>> messageWriters;
|
||||
|
||||
public SentinelBlockExceptionHandler(List<ViewResolver> viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {
|
||||
this.viewResolvers = viewResolvers;
|
||||
this.messageWriters = serverCodecConfigurer.getWriters();
|
||||
}
|
||||
|
||||
private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
|
||||
return response.writeTo(exchange, contextSupplier.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
|
||||
if (exchange.getResponse().isCommitted()) {
|
||||
return Mono.error(ex);
|
||||
}
|
||||
// This exception handler only handles rejection by Sentinel.
|
||||
if (!BlockException.isBlockException(ex)) {
|
||||
return Mono.error(ex);
|
||||
}
|
||||
return handleBlockedRequest(exchange, ex)
|
||||
.flatMap(response -> writeResponse(response, exchange));
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> handleBlockedRequest(ServerWebExchange exchange, Throwable throwable) {
|
||||
return WebFluxCallbackManager.getBlockHandler().handleRequest(exchange, throwable);
|
||||
}
|
||||
|
||||
private final Supplier<ServerResponse.Context> contextSupplier = () -> new ServerResponse.Context() {
|
||||
@Override
|
||||
public List<HttpMessageWriter<?>> messageWriters() {
|
||||
return SentinelBlockExceptionHandler.this.messageWriters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ViewResolver> viewResolvers() {
|
||||
return SentinelBlockExceptionHandler.this.viewResolvers;
|
||||
}
|
||||
};
|
||||
}
|
@@ -0,0 +1,213 @@
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.WebFluxCallbackManager;
|
||||
import com.alibaba.csp.sentinel.adapter.spring.webflux.test.WebFluxTestApplication;
|
||||
import com.alibaba.csp.sentinel.node.ClusterNode;
|
||||
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
|
||||
import com.alibaba.csp.sentinel.util.StringUtil;
|
||||
|
||||
import org.hamcrest.core.StringContains;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* @author Eric Zhao
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WebFluxTestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
public class SentinelWebFluxIntegrationTest {
|
||||
|
||||
private static final String HELLO_STR = "Hello!";
|
||||
private static final String BLOCK_MSG_PREFIX = "Blocked by Sentinel: ";
|
||||
|
||||
@Autowired
|
||||
private WebTestClient webClient;
|
||||
|
||||
private void configureRulesFor(String resource, int count) {
|
||||
configureRulesFor(resource, count, "default");
|
||||
}
|
||||
|
||||
private void configureRulesFor(String resource, int count, String limitApp) {
|
||||
FlowRule rule = new FlowRule()
|
||||
.setCount(count)
|
||||
.setGrade(RuleConstant.FLOW_GRADE_QPS);
|
||||
rule.setResource(resource);
|
||||
if (StringUtil.isNotBlank(limitApp)) {
|
||||
rule.setLimitApp(limitApp);
|
||||
}
|
||||
FlowRuleManager.loadRules(Collections.singletonList(rule));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWebFluxFilterBasic() throws Exception {
|
||||
String url = "/hello";
|
||||
this.webClient.get()
|
||||
.uri(url)
|
||||
.accept(MediaType.TEXT_PLAIN)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).isEqualTo(HELLO_STR);
|
||||
|
||||
ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
|
||||
assertNotNull(cn);
|
||||
assertEquals(1, cn.passQps(), 0.01);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWebFluxRouterFunction() throws Exception {
|
||||
|
||||
String url = "/router/hello";
|
||||
this.webClient.get()
|
||||
.uri(url)
|
||||
.accept(MediaType.TEXT_PLAIN)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).isEqualTo(HELLO_STR);
|
||||
|
||||
ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
|
||||
assertNotNull(cn);
|
||||
assertEquals(1, cn.passQps(), 0.01);
|
||||
|
||||
configureRulesFor(url, 0);
|
||||
this.webClient.get()
|
||||
.uri(url)
|
||||
.accept(MediaType.TEXT_PLAIN)
|
||||
.exchange()
|
||||
.expectStatus().isEqualTo(HttpStatus.TOO_MANY_REQUESTS)
|
||||
.expectBody(String.class).value(StringContains.containsString(BLOCK_MSG_PREFIX));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomizedUrlCleaner() throws Exception {
|
||||
final String fooPrefix = "/foo/";
|
||||
String url1 = fooPrefix + 1;
|
||||
String url2 = fooPrefix + 2;
|
||||
WebFluxCallbackManager.setUrlCleaner(((exchange, originUrl) -> {
|
||||
if (originUrl.startsWith(fooPrefix)) {
|
||||
return "/foo/*";
|
||||
}
|
||||
return originUrl;
|
||||
}));
|
||||
this.webClient.get()
|
||||
.uri(url1)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).isEqualTo("Hello 1");
|
||||
this.webClient.get()
|
||||
.uri(url2)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).isEqualTo("Hello 2");
|
||||
|
||||
ClusterNode cn = ClusterBuilderSlot.getClusterNode(fooPrefix + "*");
|
||||
assertEquals(2, cn.passQps(), 0.01);
|
||||
assertNull(ClusterBuilderSlot.getClusterNode(url1));
|
||||
assertNull(ClusterBuilderSlot.getClusterNode(url2));
|
||||
|
||||
WebFluxCallbackManager.resetUrlCleaner();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomizedIgnoreUrlCleaner() throws Exception {
|
||||
final String fooPrefix = "/foo/";
|
||||
String url1 = fooPrefix + 1;
|
||||
WebFluxCallbackManager.setUrlCleaner(((exchange, originUrl) -> {
|
||||
if (originUrl.startsWith(fooPrefix)) {
|
||||
return "";
|
||||
}
|
||||
return originUrl;
|
||||
}));
|
||||
this.webClient.get()
|
||||
.uri(url1)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).isEqualTo("Hello 1");
|
||||
|
||||
assertNull(ClusterBuilderSlot.getClusterNode(url1));
|
||||
WebFluxCallbackManager.resetUrlCleaner();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomizedBlockRequestHandler() throws Exception {
|
||||
String url = "/error";
|
||||
String prefix = "blocked: ";
|
||||
WebFluxCallbackManager.setBlockHandler((exchange, t) -> ServerResponse.ok()
|
||||
.contentType(MediaType.TEXT_PLAIN)
|
||||
.syncBody(prefix + t.getMessage()));
|
||||
|
||||
this.webClient.get()
|
||||
.uri(url)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).value(StringContains.containsString(prefix));
|
||||
|
||||
WebFluxCallbackManager.resetBlockHandler();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomizedRequestOriginParser() throws Exception {
|
||||
String url = "/hello";
|
||||
String limitOrigin = "userA";
|
||||
final String headerName = "S-User";
|
||||
configureRulesFor(url, 0, limitOrigin);
|
||||
|
||||
WebFluxCallbackManager.setRequestOriginParser(exchange -> {
|
||||
String origin = exchange.getRequest().getHeaders().getFirst(headerName);
|
||||
return origin != null ? origin : "";
|
||||
});
|
||||
|
||||
this.webClient.get()
|
||||
.uri(url)
|
||||
.accept(MediaType.TEXT_PLAIN)
|
||||
.header(headerName, "userB")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).isEqualTo(HELLO_STR);
|
||||
// This will be blocked.
|
||||
this.webClient.get()
|
||||
.uri(url)
|
||||
.accept(MediaType.TEXT_PLAIN)
|
||||
.header(headerName, limitOrigin)
|
||||
.exchange()
|
||||
.expectStatus().isEqualTo(HttpStatus.TOO_MANY_REQUESTS)
|
||||
.expectBody(String.class).value(StringContains.containsString(BLOCK_MSG_PREFIX));
|
||||
this.webClient.get()
|
||||
.uri(url)
|
||||
.accept(MediaType.TEXT_PLAIN)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).isEqualTo(HELLO_STR);
|
||||
|
||||
WebFluxCallbackManager.resetRequestOriginParser();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
FlowRuleManager.loadRules(new ArrayList<>());
|
||||
ClusterBuilderSlot.resetClusterNodes();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanUp() {
|
||||
FlowRuleManager.loadRules(new ArrayList<>());
|
||||
ClusterBuilderSlot.resetClusterNodes();
|
||||
}
|
||||
}
|
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright 1999-2019 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux.test;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* @author Eric Zhao
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class WebFluxTestApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebFluxTestApplication.class, args);
|
||||
}
|
||||
}
|
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright 1999-2019 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux.test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.spring.webflux.SentinelWebFluxFilter;
|
||||
import com.alibaba.csp.sentinel.adapter.spring.webflux.exception.SentinelBlockExceptionHandler;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.codec.ServerCodecConfigurer;
|
||||
import org.springframework.web.reactive.result.view.ViewResolver;
|
||||
|
||||
/**
|
||||
* @author Eric Zhao
|
||||
*/
|
||||
@Configuration
|
||||
public class WebFluxTestConfig {
|
||||
|
||||
private final List<ViewResolver> viewResolvers;
|
||||
private final ServerCodecConfigurer serverCodecConfigurer;
|
||||
|
||||
public WebFluxTestConfig(ObjectProvider<List<ViewResolver>> viewResolversProvider,
|
||||
ServerCodecConfigurer serverCodecConfigurer) {
|
||||
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
|
||||
this.serverCodecConfigurer = serverCodecConfigurer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(-1)
|
||||
public SentinelBlockExceptionHandler sentinelBlockExceptionHandler() {
|
||||
// Register the block exception handler for Spring WebFlux.
|
||||
return new SentinelBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(-1)
|
||||
public SentinelWebFluxFilter sentinelWebFluxFilter() {
|
||||
// Register the Sentinel WebFlux filter.
|
||||
return new SentinelWebFluxFilter();
|
||||
}
|
||||
}
|
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright 1999-2019 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux.test;
|
||||
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* @author Eric Zhao
|
||||
*/
|
||||
@RestController
|
||||
public class WebFluxTestController {
|
||||
|
||||
@GetMapping("/hello")
|
||||
public String apiHello() {
|
||||
return "Hello!";
|
||||
}
|
||||
|
||||
@GetMapping("/flux")
|
||||
public Flux<Integer> apiFlux() {
|
||||
return Flux.range(0, 5);
|
||||
}
|
||||
|
||||
@GetMapping("/error")
|
||||
public Mono<?> apiError() {
|
||||
return Mono.error(new FlowException("testWebFluxError"));
|
||||
}
|
||||
|
||||
@GetMapping("/foo/{id}")
|
||||
public String apiFoo(@PathVariable("id") Long id) {
|
||||
return "Hello " + id;
|
||||
}
|
||||
}
|
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 1999-2020 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.csp.sentinel.adapter.spring.webflux.test;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
|
||||
|
||||
/**
|
||||
* @author liqiangz
|
||||
*/
|
||||
@Configuration
|
||||
public class WebFluxTestRouter {
|
||||
|
||||
@Bean
|
||||
RouterFunction<ServerResponse> routingFunction() {
|
||||
return route(GET("/router/hello"),
|
||||
req -> ServerResponse.ok().body(fromObject("Hello!")));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user