Contents

Microservices

Spring Cloud

Spring Cloud Alibaba Sentinel provides out-of-box integration with Sentinel for Spring Cloud applications and services (Spring Web, Spring WebFlux, RestTemplate, Feign, Spring Cloud Gateway, Reactor, Zuul).

Please refer to Spring Cloud Alibaba for more information. Demo: sentinel-guide-spring-cloud

Quarkus

Sentinel provides out-of-box support for Quarkus. See sentinel-quarkus-adapter for more details (since 1.8.0).

Web frameworks

Web Servlet

Sentinel provides Web Servlet filter integration to enable flow control for web requests. Add the following dependency in pom.xml (if you are using Maven):

  1. <dependency>
  2. <groupId>com.alibaba.csp</groupId>
  3. <artifactId>sentinel-web-servlet</artifactId>
  4. <version>x.y.z</version>
  5. </dependency>

To use the filter, you can simply configure your web.xml with:

  1. <filter>
  2. <filter-name>SentinelCommonFilter</filter-name>
  3. <filter-class>com.alibaba.csp.sentinel.adapter.servlet.CommonFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>SentinelCommonFilter</filter-name>
  7. <url-pattern>/*</url-pattern>
  8. </filter-mapping>

For Spring web applications you can configure with Spring bean:

  1. @Configuration
  2. public class FilterConfig {
  3. @Bean
  4. public FilterRegistrationBean sentinelFilterRegistration() {
  5. FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
  6. registration.setFilter(new CommonFilter());
  7. registration.addUrlPatterns("/*");
  8. registration.setName("sentinelFilter");
  9. registration.setOrder(1);
  10. return registration;
  11. }
  12. }

When a request is blocked, Sentinel servlet filter will give a default page indicating the request blocked. If customized block page is set (via WebServletConfig.setBlockPage(blockPage) method), the filter will redirect the request to provided URL. You can also implement your own block handler (the UrlBlockHandler interface) and register to WebCallbackManager.

The UrlCleaner interface is designed to clean and unify the URL resource. For REST APIs, you have to clean the URL resource (e.g. /foo/1 and /foo/2 -> /foo/:id), or the amount of context and resources will exceed the threshold.

The RequestOriginParser interface is useful for extracting request origin (e.g. IP or appName from HTTP Header) from the HTTP request. You can implement your own RequestOriginParser and register to WebCallbackManager.

Spring WebFlux

Note: supported since Sentinel 1.5.0. This module requires JDK 8 or later versions.

See the document of Sentinel Spring WebFlux Adapter module.

RPC frameworks

Dubbo

Sentinel Dubbo Adapter provides service consumer filter and provider filter for Dubbo services. Since Dubbo 2.7.x is not compatible with the previous version, we provide two modules:

  • sentinel-apache-dubbo-adapter (compatible with Apache Dubbo 2.7.x and later version, supported since Sentinel 1.5.1)
  • sentinel-dubbo-adapter (compatible with Dubbo 2.6.x and previous version)

If you are using Apache Dubbo 2.7.x and later version, you can add the following dependency:

  1. <dependency>
  2. <groupId>com.alibaba.csp</groupId>
  3. <artifactId>sentinel-apache-dubbo-adapter</artifactId>
  4. <version>x.y.z</version>
  5. </dependency>

If you are using Dubbo 2.6.x or previous version, you can add the following dependency:

  1. <dependency>
  2. <groupId>com.alibaba.csp</groupId>
  3. <artifactId>sentinel-dubbo-adapter</artifactId>
  4. <version>x.y.z</version>
  5. </dependency>

The adapter filters are enabled by default. Once you add the dependency, the Dubbo services and methods will become protected resources in Sentinel, which can leverage Sentinel’s flow control and guard ability when rules are configured.

If you don’t want to enable the filter, you can manually disable it. For example:

  1. <!-- disable the Sentinel Dubbo consumer filter -->
  2. <dubbo:consumer filter="-sentinel.dubbo.consumer.filter"/>

The guarded resource can be both service interface and service method:

  • Service interface:resourceName format is interfaceName,e.g. com.alibaba.csp.sentinel.demo.dubbo.FooService
  • Service method:resourceName format is interfaceName:methodSignature,e.g. com.alibaba.csp.sentinel.demo.dubbo.FooService:sayHello(java.lang.String)

Sentinel Dubbo Adapter supports global fallback configuration. The global fallback will handle exceptions and give the replacement result when blocked by flow control, degrade or system load protection. You can implement your own DubboFallback interface and then register to DubboFallbackRegistry. If no fallback is configured, Sentinel will wrap the BlockException then directly throw it out. Besides, we can also leverage Dubbo mock mechanism to provide the fallback implementation of degraded Dubbo services.

For Sentinel’s best practice in Dubbo, please refer to Sentinel: the flow sentinel of Dubbo.

For more details of Dubbo filter, see here.

gRPC

Sentinel provides integration with gRPC Java. Sentinel gRPC Adapter provides client and server interceptor for gRPC services. Add the following dependency in pom.xml (if you are using Maven):

  1. <dependency>
  2. <groupId>com.alibaba.csp</groupId>
  3. <artifactId>sentinel-grpc-adapter</artifactId>
  4. <version>x.y.z</version>
  5. </dependency>

To use Sentinel gRPC Adapter, you simply need to register the Interceptor to your client or server. The client sample:

  1. public class ServiceClient {
  2. private final ManagedChannel channel;
  3. ServiceClient(String host, int port) {
  4. this.channel = ManagedChannelBuilder.forAddress(host, port)
  5. .intercept(new SentinelGrpcClientInterceptor()) // Add the client interceptor.
  6. .build();
  7. // Init your stub here.
  8. }
  9. }

The server sample;

  1. import io.grpc.Server;
  2. Server server = ServerBuilder.forPort(port)
  3. .addService(new MyServiceImpl()) // Add your service.
  4. .intercept(new SentinelGrpcServerInterceptor()) // Add the server interceptor.
  5. .build();

Note that currently the interceptor only supports unary methods in gRPC.

Reactive support

Reactor

Note: supported since Sentinel 1.5.0. This module requires JDK 8 or later versions.

Sentinel provides integration module for Reactor.

Add the following dependency in pom.xml (if you are using Maven):

  1. <dependency>
  2. <groupId>com.alibaba.csp</groupId>
  3. <artifactId>sentinel-reactor-adapter</artifactId>
  4. <version>x.y.z</version>
  5. </dependency>

Example:

  1. someService.doSomething() // return type: Mono<T> or Flux<T>
  2. .transform(new SentinelReactorTransformer<>(resourceName)) // transform here
  3. .subscribe();

API Gateway support

Spring Cloud Gateway

Note: this module requires Java 8 or later version.

Sentinel provides an integration module with Spring Cloud Gateway, which supports flow control for routes and customized API groups. The integration module is based on the Sentinel Reactor Adapter.

Add the following dependency in pom.xml (if you are using Maven):

  1. <dependency>
  2. <groupId>com.alibaba.csp</groupId>
  3. <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
  4. <version>x.y.z</version>
  5. </dependency>

Then you only need to inject the corresponding SentinelGatewayFilter and SentinelGatewayBlockExceptionHandler instance in Spring configuration. For example:

  1. @Configuration
  2. public class GatewayConfiguration {
  3. private final List<ViewResolver> viewResolvers;
  4. private final ServerCodecConfigurer serverCodecConfigurer;
  5. public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
  6. ServerCodecConfigurer serverCodecConfigurer) {
  7. this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
  8. this.serverCodecConfigurer = serverCodecConfigurer;
  9. }
  10. @Bean
  11. @Order(-1)
  12. public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
  13. // Register the block exception handler for Spring Cloud Gateway.
  14. return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
  15. }
  16. @Bean
  17. @Order(-1)
  18. public GlobalFilter sentinelGatewayFilter() {
  19. return new SentinelGatewayFilter();
  20. }
  21. }

The gateway adapter will regard all routeId (defined in Spring properties) and all customized API definitions (defined in GatewayApiDefinitionManager of sentinel-api-gateway-adapter-common module) as resources.

You can register various customized callback in GatewayCallbackManager:

  • setBlockHandler: register a customized BlockRequestHandler to handle the blocked request. The default implementation is DefaultBlockRequestHandler, which returns default message like Blocked by Sentinel: FlowException.

Zuul 1.x

Sentinel Zuul Adapter provides route level and customized API level flow control for Zuul 1.x. Please refer to the document here.

Apache RocketMQ

In Apache RocketMQ, when message consumers are consuming messages, there may a sudden inflow of messages, whether using pull or push mode. If all the messages were handled at this time, it would be likely to cause the system to be overloaded and then affect stability. However, in fact, there may be no messages coming within a few seconds. If redundant messages are directly discarded, the system’s ability to process the message is not fully utilized. We hope that the sudden inflow of messages can be spread over a period of time, so that the system load can be kept on the stable level while processing as many messages as possible, thus achieving the effect of “shaving the peaks and filling the valley”.

shaving the peaks and filling the valley

Sentinel provides a feature for this kind of scenario: Rate Limiter, which can spread a large number of sudden request inflow in a uniform rate manner, let the request pass at a fixed interval. It is often used to process burst requests instead of rejecting them. This avoids traffic spurs causing system overloaded. Moreover, the pending requests will be queued and processed one by one. When the request is estimated to exceed the maximum queuing timeout, it will be rejected immediately.

For example, we configure the rule with uniform rate limiting mode and QPS count is 5, which indicates messages are consumed at fixed interval (200 ms) and pending messages will wait (virtual queue). We also set the maximum queuing timeout is 5s, then all requests estimated to exceed the timeout will be rejected immediately.

Uniform rate

Developer can set rules to different groups and topics (e.g. resouceName is groupName:topicName), set the control behaviour to RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER, then the messages can be handled at a fixed rate. Here is an example for the rule:

  1. private void initFlowControlRule() {
  2. FlowRule rule = new FlowRule();
  3. rule.setResource(KEY); // resource name can be `groupName:topicName`
  4. rule.setCount(5); // Indicates the interval between two adjacent requests is 200 ms.
  5. rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
  6. rule.setLimitApp("default");
  7. // Enable rate limiting (uniform). This can ensure fixed intervals between two adjacent calls.
  8. // In this example, intervals between two incoming calls (message consumption) will be 200 ms constantly.
  9. rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
  10. // If more requests are coming, they'll be put into the waiting queue.
  11. // In this example, the max timeout is 5s.
  12. rule.setMaxQueueingTimeMs(5 * 1000);
  13. FlowRuleManager.loadRules(Collections.singletonList(rule));
  14. }

When using Sentinel with RocketMQ Client, developers should manually wrap their code of handling messages with Sentinel API. Here is a sample for pull consumer: Sentinel RocketMQ Demo.