Contents

Introduction

To use Sentinel, you only need to complete 2 steps:

  1. Define resources
  2. Configure rules

These two steps don’t have to be synchronized. As long as the resources are defined, you can add rules as needed. Multiple rules can be applied to the same resource simultaneously.

Sentinel provides integrations with popular open-source frameworks and libraries as well (e.g. Spring Cloud, gRPC, Dubbo, Spring WebFlux, Reactor). After introducing these integrations, services and methods provided by these frameworks are defined as resources by default.

Define Resource

You can use one of the following approaches to define resources.

“try” and “catch” mode

Since 1.5.0 we can leverage try-with-resources feature of JDK 1.7:

  1. try (Entry entry = SphU.entry("resourceName")) {
  2. // do something here (your business logic)...
  3. } catch (BlockException ex) {
  4. // Here to handle the rejection
  5. }

Before 1.5.0:

  1. Entry entry = null;
  2. try {
  3. entry = SphU.entry(resourceName);
  4. // Your business logic here.
  5. } catch (BlockException ex) {
  6. // The invocation is rejected.
  7. // Here to handle the block exception
  8. } finally {
  9. // DO NOT forget to exit the entry!
  10. if (entry != null) {
  11. entry.exit(); // Mark as completed.
  12. }
  13. }

Bool mode

  1. if (SphO.entry(resourceName)) {
  2. try {
  3. // Your code logic here.
  4. } finally {
  5. SphO.exit();
  6. }
  7. } else {
  8. // Resource is rejected.
  9. // Your logic to handle blocking here.
  10. }
  11. }

Annotation mode

Sentinel supports defining resources with @SentinelResource annotation. See annotation support for guidelines.

Check block exception

You can check whether an exception is caused by Sentinel’s flow control (BlockException) via:

  1. BlockException.isBlockException(Throwable t);

Integrations with open-source frameworks

For details, please refer to Adapters to popular frameworks.

Resource for asynchronous entries

Here is a simple example:

  1. try {
  2. AsyncEntry entry = SphU.asyncEntry(resourceName);
  3. // Asynchronous invocation.
  4. doAsync(userId, result -> {
  5. try {
  6. // Handle your asynchronous result here.
  7. } finally {
  8. // Exit after callback completed.
  9. entry.exit();
  10. }
  11. });
  12. } catch (BlockException ex) {
  13. // Request blocked.
  14. // Handle the exception (e.g. retry or fallback).
  15. }

For more advanced usage, you can refer to AsyncEntryDemo.

Configure Rules

Sentinel provides APIs for you to modify your rules, which can be integrated with various kinds of rule repository, such as configuration server and NoSQL.

Definition of Rules

There are 4 types of rules:flow control rules, degrade rules, system protection rules and authority rules.

Flow control rules (FlowRule)

Definition

key fields:

FieldDescriptionDefault value
resourceresource name
countthreshold
gradeflow control metric (QPS or concurrent thread count)QPS
limitApprefer to specified callerdefault
strategyby resource itself or other resource (refResource),or entry (refResource)resource itself
controlBehaviortraffic shaping control behavior (reject directly,queue,slow start up)reject directly

Multiple rules can be applied to the same resource.

API

FlowRuleManager.loadRules() can be used to configure flow control rules.

  1. private static void initFlowQpsRule() {
  2. List<FlowRule> rules = new ArrayList<FlowRule>();
  3. FlowRule rule1 = new FlowRule();
  4. rule1.setResource(KEY);
  5. // set limit qps to 20
  6. rule1.setCount(20);
  7. rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
  8. rule1.setLimitApp("default");
  9. rules.add(rule1);
  10. FlowRuleManager.loadRules(rules);
  11. }

For more details please refer to Flow Control.

Circuit breaking rules (DegradeRule)

Key fields:

FieldDescriptionDefault value
resourceresource name
countthreshold
gradecircuit breaking strategy (slow request ratio/error ratio/error count)slow request ratio
timeWindowcircuit breaker recovery timeout (in second)
minRequestAmountthe minimum number of calls that are required (per sliding window period) before the circuit breaker can calculate the ratio or total amount (since 1.7.0)5
statIntervalMssliding window period (since 1.8.0)1000
slowRatioThresholdthreshold of the slow ratio, only available for slow ratio strategy (since 1.8.0)

Multiple rules can be applied to the same resource.

API

DegradeRuleManager.loadRules() can be used to configure degrade rules.

  1. private static void initDegradeRule() {
  2. List<DegradeRule> rules = new ArrayList<DegradeRule>();
  3. DegradeRule rule = new DegradeRule();
  4. rule.setResource(KEY);
  5. // set threshold rt, 10 ms
  6. rule.setCount(10);
  7. rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
  8. rule.setTimeWindow(10);
  9. rules.add(rule);
  10. DegradeRuleManager.loadRules(rules);
  11. }

For more details, please refer to Circuit Breaking.

System protection rules (SystemRule)

Key factors

FieldDescriptionDefault value
highestSystemLoadthreshold of Load1-1(not valid)
avgRtaverage response time-1(not valid)
maxThreadconcurrent thread count-1(not valid)

API

SystemRuleManager.loadRules() can be used to configure system protection rules.

  1. private void initSystemProtectionRule() {
  2. List<SystemRule> rules = new ArrayList<>();
  3. SystemRule rule = new SystemRule();
  4. rule.setHighestSystemLoad(10);
  5. rules.add(rule);
  6. SystemRuleManager.loadRules(rules);
  7. }

For more details, please refer to Adaptive System Protection.

HTTP commands for rules

You can also use HTTP API to configure, query and update Sentinel rules.

To use these API, make sure that the following library has been introduced:

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

Query command

API:

  1. curl http://localhost:8719/getRules?type=<XXXX>
  • type=flow for flow rules;
  • type=degrade for circuit breaking rules;
  • type=system for system protection rules.

Rules will be returned in JSON format.

Modification command

Note: Only for test, do not use in production.

  1. curl http://localhost:8719/setRules?type=<XXXX>&data=<DATA>

Integrate with rule repositories

DataSource is designed to integrate rules to customized repositories and make rules persistent.

For more details, you can refer to Dynamic Rule Configuration.