Skip to content

Sentinel en

Eric Zhao edited this page Jan 15, 2020 · 3 revisions

Spring Cloud Alibaba Sentinel

Introduction of Sentinel

As distributed systems become increasingly popular, the reliability between services is becoming more important than ever before. Sentinel takes "flow" as the breakthrough point, and works on multiple fields including flow control, circuit breaking and system adaptive protection, to guarantee the reliability of microservices.

Sentinel has the following features:

  • Rich applicable scenarios: Sentinel has been wildly used in Alibaba, and has covered almost all the core-scenarios in Double-11 (11.11) Shopping Festivals in the past 10 years, such as “Second Kill” which needs to limit burst flow traffic to meet the system capacity, message peak clipping and valley fills, circuit breaking for unreliable downstream services, cluster flow control, etc.

  • Real-time monitoring: Sentinel also provides real-time monitoring ability. You can see the runtime information of a single machine in real-time, and the aggregated runtime info of a cluster with less than 500 nodes.

  • Widespread open-source ecosystem: Sentinel provides out-of-box integrations with commonly-used frameworks and libraries such as Spring Cloud, Dubbo and gRPC. You can easily use Sentinel by simply add the adapter dependency to your services.

  • Various SPI extensions: Sentinel provides easy-to-use SPI extension interfaces that allow you to quickly customize your logic, for example, custom rule management, adapting data sources, and so on.

How to Use Sentinel

If you want to use Sentinel in your project, please use the starter with the group ID as com.alibaba.cloud and the artifact ID as spring-cloud-starter-alibaba-sentinel.

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

The following is a simple example of how to use Sentinel:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }
}

@Service
public class TestService {

    @SentinelResource(value = "sayHello")
    public String sayHello(String name) {
        return "Hello, " + name;
    }
}

@RestController
public class TestController {

    @Autowired
    private TestService service;

    @GetMapping(value = "/hello/{name}")
    public String apiHello(@PathVariable String name) {
        return service.sayHello(name);
    }
}

The @SentinelResource annotation is used to wrap your logic as the guarded resource of Sentinel. In the above sample, the sayHello attribute of the annotation refers to the resource name.

@SentinelResource also provides attributes such as blockHandler, blockHandlerClass, and fallback to identify the handler logic of flow control. For more details, refer to the document of Sentinel Annotation Support.

The above examples are all used in the Web Servlet environment. Sentinel currently supports Spring WebFlux and needs to cooperate with the spring-boot-starter-webflux dependency to trigger the WebFlux-related automation configuration in Sentinel starter.

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }

}

@RestController
public class TestController {

    @GetMapping("/mono")
    public Mono<String> mono() {
	return Mono.just("simple string");
    }

}
Sentinel Dashboard

Sentinel provides a simple stand-alone dashboard, on which you can monitor your services, and configure the rules in real-time. It includes the following features:

  • Machine discovery

  • Real-time monitoring for a single machine or clusters with less than 500 nodes

  • Rule management

  • Token server/client management for cluster flow control

55449295 84866d80 55fd 11e9 94e5 d3441f4a2b63
Figure 1. Sentinel Dashboard

To use the Sentinel dashboard, simply complete the following 3 steps.

Get the Dashboard

You can download the latest dashboard JAR file from the Release Page.

You can also get the latest source code to build your own Sentinel dashboard:

  • Download the Dashboard project.

  • Run the following command to package the code into a fat-jar: mvn clean package (dashboard/en branch to build English version)

Start the Dashboard

Sentinel dashboard is a standard Spring Boot application, and you can run the JAR file in the Spring Boot mode.

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar

If there are conflicts with the 8080 port, you can use -Dserver.port=new port to define a new port.

Configure the Dashboard

application.yml
spring:
  cloud:
    sentinel:
      transport:
        port: 8719
        dashboard: localhost:8080

The port number specified in spring.cloud.sentinel.transport.port will start an HTTP Server on the corresponding server of the application, and this server will interact with the Sentinel dashboard. For example, if a flow rule is added in the Sentinel dashboard, the rule data will be pushed to and received by the HTTP Server, which in turn registers the rule to Sentinel.

For more information about Sentinel dashboard, please refer to Sentinel Dashboard.

OpenFeign Support

Sentinel is compatible with the OpenFeign component. To use it, in addition to introducing the sentinel-starter dependency, complete the following 2 steps:

  • Enable the Sentinel support for feign in the properties file. feign.sentinel.enabled=true

  • Add the openfeign starter dependency to trigger and enable the Sentinel starter:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

This is a simple usage of FeignClient:

@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class)
public interface EchoService {
    @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
    String echo(@PathVariable("str") String str);
}

class FeignConfiguration {
    @Bean
    public EchoServiceFallback echoServiceFallback() {
        return new EchoServiceFallback();
    }
}

class EchoServiceFallback implements EchoService {
    @Override
    public String echo(@PathVariable("str") String str) {
        return "echo fallback";
    }
}
Note
The resource name policy in the corresponding interface of Feign is:httpmethod:protocol://requesturl. All the attributes in the @FeignClient annotation are supported by Sentinel.

The corresponding resource name of the echo method in the EchoService interface is GET:http://service-provider/echo/{str}.

RestTemplate Support

Spring Cloud Alibaba Sentinel supports the protection of RestTemplate service calls using Sentinel. To do this, you need to add the @SentinelRestTemplate annotation when constructing the RestTemplate bean.

@Bean
@SentinelRestTemplate(blockHandler = "handleException", blockHandlerClass = ExceptionUtil.class)
public RestTemplate restTemplate() {
    return new RestTemplate();
}

The attribute of the @SentinelRestTemplate annotation support flow control(blockHandler, blockHandlerClass) and circuit breaking(fallback, fallbackClass).

==

The blockHandler or fallback is the static method of blockHandlerClass or fallbackClass.

The parameter and return value of method in @SentinelRestTemplate is same as org.springframework.http.client.ClientHttpRequestInterceptor#interceptor, but it has one more parameter BlockException to catch the exception by Sentinel.

The method signature of handleException in ExceptionUtil above should be like this:

public class ExceptionUtil {
    public static ClientHttpResponse handleException(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException exception) {
        ...
    }
}
Note
When the application starts, it will check if the @SentinelRestTemplate annotation corresponding to the flow control or circuit breaking method exists, if it does not exist, it will throw an exception.

The attribute of the @SentinelRestTemplate annotation is optional.

It will return RestTemplate request block by sentinel when you using RestTemplate blocked by Sentinel. You can override it by your own logic. We provide SentinelClientHttpResponse to handle the response.

Sentinel RestTemplate provides two granularities for resource rate limiting:

  • httpmethod:schema://host:port/path: Protocol, host, port and path

  • httpmethod:schema://host:port: Protocol, host and port

Note
Take Http GET https://www.taobao.com/test as an example. The corresponding resource names have two levels of granularities, GET:https://www.taobao.com and GET:https://www.taobao.com/test.

Dynamic Data Source Support

SentinelProperties provide datasource attribute to configure datasource.

For example, 4 data sources are configures:

spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

#spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
#spring.cloud.sentinel.datasource.ds1.file.data-type=custom
#spring.cloud.sentinel.datasource.ds1.file.converter-class=JsonFlowRuleListConverter
#spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

spring.cloud.sentinel.datasource.ds2.nacos.server-addr=localhost:8848
spring.cloud.sentinel.datasource.ds2.nacos.data-id=sentinel
spring.cloud.sentinel.datasource.ds2.nacos.group-id=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=degrade

spring.cloud.sentinel.datasource.ds3.zk.path = /Sentinel-Demo/SYSTEM-CODE-DEMO-FLOW
spring.cloud.sentinel.datasource.ds3.zk.server-addr = localhost:2181
spring.cloud.sentinel.datasource.ds3.zk.rule-type=authority

spring.cloud.sentinel.datasource.ds4.apollo.namespace-name = application
spring.cloud.sentinel.datasource.ds4.apollo.flow-rules-key = sentinel
spring.cloud.sentinel.datasource.ds4.apollo.default-flow-rule-value = test
spring.cloud.sentinel.datasource.ds4.apollo.rule-type=param-flow

This method follows the configuration of Spring Cloud Stream Binder. TreeMap is used for storage internally, and comparator is String.CASE_INSENSITIVE_ORDER.

Note
d1, ds2, ds3, ds4 are the names of ReadableDataSource, and can be coded as you like. The file, zk, nacos , apollo refer to the specific data sources. The configurations following them are the specific configurations of these data sources respecitively.

Every data source has 3 common configuration items: data-type, converter-class and rule-type.

data-type refers to Converter. Spring Cloud Alibaba Sentinel provides two embedded values by default: json and xml (the default is JSON if not specified). If you do not want to use the embedded json or xml Converter, you can also fill in custom to indicate that you will define your own Converter, and then configure the converter-class. You need to specify the full path of the class for this configuration.

rule-type refers to the rule type in datasource(flowdegradeauthoritysystem, param-flow, gw-flow, gw-api-group).

Note
XML format is not supported by default. To make it effective, you need to add the jackson-dataformat-xml dependency.

To learn more about how dynamic data sources work in Sentinel, refer to Dynamic Rule Extension.

Support Zuul

If you want to use Sentinel Starter with Zuul 1.x, you need to add the spring-cloud-alibaba-sentinel-gateway dependency, and you need to add the spring-cloud-starter-netflix-zuul dependency to let Zuul AutoConfiguration class in the gateway module takes effect:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

Support Spring Cloud Gateway

If you want to use Sentinel Starter with Spring Cloud Gateway, you need to add the spring-cloud-alibaba-sentinel-gateway dependency and add the spring-cloud-starter-gateway dependency to let Spring Cloud Gateway AutoConfiguration class in the module takes effect:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

Sentinel Endpoint

Sentinel provides an Endpoint internally with a corresponding endpoint id of sentinel.

Endpoint exposed json contains multi properties:

  1. appName: application name

  2. logDir: the directory of log

  3. logUsePid: log name with pid ot not

  4. blockPage: redirect page after sentinel block

  5. metricsFileSize: the size of metrics file

  6. metricsFileCharset: metrics file charset

  7. totalMetricsFileCount: the total file count of of metrics file

  8. consoleServer: sentinel dashboard address

  9. clientIp: client ip

  10. heartbeatIntervalMs: client heartbeat interval with dashboard

  11. clientPort: the client needs to expose the port to interact with the dashboard

  12. coldFactor: cold factor

  13. filter: CommonFilter related properties, such as order, urlPatterns and enable

  14. datasource: datasource configuration info by client

  15. rules: the rule that the client takes effect internally contains flowRules, degradeRules, systemRules, authorityRule, paramFlowRule

The followings shows how a service instance accesses the Endpoint:

{
	"blockPage": null,
	"appName": "sentinel-example",
	"consoleServer": "localhost:8080",
	"coldFactor": "3",
	"rules": {
		"flowRules": [{
			"resource": "GET:http://www.taobao.com",
			"limitApp": "default",
			"grade": 1,
			"count": 0.0,
			"strategy": 0,
			"refResource": null,
			"controlBehavior": 0,
			"warmUpPeriodSec": 10,
			"maxQueueingTimeMs": 500,
			"clusterMode": false,
			"clusterConfig": null
		}, {
			"resource": "/test",
			"limitApp": "default",
			"grade": 1,
			"count": 0.0,
			"strategy": 0,
			"refResource": null,
			"controlBehavior": 0,
			"warmUpPeriodSec": 10,
			"maxQueueingTimeMs": 500,
			"clusterMode": false,
			"clusterConfig": null
		}, {
			"resource": "/hello",
			"limitApp": "default",
			"grade": 1,
			"count": 1.0,
			"strategy": 0,
			"refResource": null,
			"controlBehavior": 0,
			"warmUpPeriodSec": 10,
			"maxQueueingTimeMs": 500,
			"clusterMode": false,
			"clusterConfig": null
		}]
	},
	"metricsFileCharset": "UTF-8",
	"filter": {
		"order": -2147483648,
		"urlPatterns": ["/*"],
		"enabled": true
	},
	"totalMetricsFileCount": 6,
	"datasource": {
		"ds1": {
			"file": {
				"dataType": "json",
				"ruleType": "FLOW",
				"converterClass": null,
				"file": "...",
				"charset": "utf-8",
				"recommendRefreshMs": 3000,
				"bufSize": 1048576
			},
			"nacos": null,
			"zk": null,
			"apollo": null,
			"redis": null
		}
	},
	"clientIp": "30.5.121.91",
	"clientPort": "8719",
	"logUsePid": false,
	"metricsFileSize": 52428800,
	"logDir": "...",
	"heartbeatIntervalMs": 10000
}

Configuration

The following table shows that when there are corresponding bean types in ApplicationContext, some actions will be taken:

Existing Bean Type Action Function

UrlCleaner

WebCallbackManager.setUrlCleaner(urlCleaner)

Resource cleaning(resource(for example, classify all URLs of /foo/:id to the /foo/* resource))

UrlBlockHandler

WebCallbackManager.setUrlBlockHandler(urlBlockHandler)

Customize rate limiting logic

RequestOriginParser

WebCallbackManager.setRequestOriginParser(requestOriginParser)

Setting the origin

The following table shows all the configurations of Spring Cloud Alibaba Sentinel:

Configuration Description Default Value

spring.application.name or project.name

Project Name Of Sentinel

spring.cloud.sentinel.enabled

Whether Sentinel automatic configuration takes effect

true

spring.cloud.sentinel.eager

Whether to trigger Sentinel initialization in advance

false

spring.cloud.sentinel.transport.port

Port for the application to interact with Sentinel dashboard. An HTTP Server which uses this port will be started in the application

8719

spring.cloud.sentinel.transport.dashboard

Sentinel dashboard address

spring.cloud.sentinel.transport.heartbeatIntervalMs

Hearbeat interval between the application and Sentinel dashboard

spring.cloud.sentinel.transport.client-ip

The client IP of this configuration will be registered to the Sentinel Server side.

spring.cloud.sentinel.filter.order

Loading order of Servlet Filter. The filter will be constructed in the Starter

Integer.MIN_VALUE

spring.cloud.sentinel.filter.url-patterns

Data type is array. Refers to the collection of Servlet Filter ULR patterns

/*

spring.cloud.sentinel.filter.enabled

Enable to instance CommonFilter

true

spring.cloud.sentinel.metric.charset

metric file character set

UTF-8

spring.cloud.sentinel.metric.fileSingleSize

Sentinel metric single file size

spring.cloud.sentinel.metric.fileTotalCount

Sentinel metric total file number

spring.cloud.sentinel.log.dir

Directory of Sentinel log files

spring.cloud.sentinel.log.switch-pid

If PID is required for Sentinel log file names

false

spring.cloud.sentinel.servlet.blockPage

Customized redirection URL. When rate limited, the request will be redirected to the pre-defined URL

spring.cloud.sentinel.flow.coldFactor

The cold factor of the warm-up mode

3

spring.cloud.sentinel.zuul.order.pre

The order of SentinelZuulPreFilter

10000

spring.cloud.sentinel.zuul.order.post

The order of SentinelZuulPostFilter

1000

spring.cloud.sentinel.zuul.order.error

The order of SentinelZuulErrorFilter

-1

spring.cloud.sentinel.scg.fallback.mode

Response mode after Spring Cloud Gateway circuit break (select redirect or response)

spring.cloud.sentinel.scg.fallback.redirect

Spring Cloud Gateway response mode is the redirect URL corresponding to 'redirect' mode

spring.cloud.sentinel.scg.fallback.response-body

Spring Cloud Gateway response mode is response content corresponding to 'response' mode

spring.cloud.sentinel.scg.fallback.response-status

Spring Cloud Gateway response mode is the response code corresponding to 'response' mode

429

spring.cloud.sentinel.scg.fallback.content-type

The Spring Cloud Gateway response mode is the content-type corresponding to the 'response' mode.

application/json

Note
These configurations will only take effect in servlet environment. RestTemplate and Feign will not take effect for these configurations.