1. background
1.1 brief introduction
Sentinel Has the following characteristics
- Rich application scenarios :Sentinel To undertake Alibaba near 10 The core scene of promoting traffic in the double 11 of , For example, seckill ( That is to say, the burst flow is controlled within the range of system capacity )、 Cut the peak and fill the valley 、 Cluster flow control 、 Real time fuse downstream unavailable applications, etc .
- Complete real-time monitoring :Sentinel At the same time, it provides real-time monitoring function . You can see the second level data of a single machine accessing the application in the console , even to the extent that 500 Summary operation of clusters below Taiwan .
- Broad open source ecosystem :Sentinel Provides out of the box and other open source frameworks / The integration module of the library , For example, Spring Cloud、Apache Dubbo、gRPC、Quarkus Integration of . You only need to introduce corresponding dependency and make simple configuration to access quickly Sentinel. meanwhile Sentinel Provide Java/Go/C++ And so on .
- Perfect SPI Extension mechanism :Sentinel Easy to use 、 Perfect SPI Extension interface . You can quickly customize the logic by implementing the extension interface . For example, custom rule management 、 Adapt to dynamic data sources, etc .
Sentinel The main characteristics of
- Core library (Java client ) Don't rely on any framework / library , Can run on all Java Runtime environment , At the same time Dubbo / Spring Cloud And other frameworks also have better support .
- Console (Dashboard) be based on Spring Boot Development , It can run directly after packing , No additional Tomcat Etc. Application containers .
1.2 Learning reference
- sentinel Official documents :《 Official document address 》
- sentinel The source code parsing :《sentinel How to limit the current 》
- sentinel General knowledge :《sentinel Chain link 17 ask 》
1.3 Chapter introduction
- be based on Spring boot docking Sentinel;
- Nacos To configure Sentinel Rule information ;
- Test flow control rules , System protection rules , Fusing rules ;
- Sentinel Console data display problem ;
- Nacos Rule storage and Sentinel Modify the data synchronization problem ;
- Sentinel Analysis of responsibility chain model
2. The project build
2.1 pom To configure
<!-- nacos To configure -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!-- sentinel To configure -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!-- sentinel Rule based nacos Storage -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
<version>1.8.3</version>
</dependency>
2.2 Project parameter configuration
server:
servlet:
context-path: /sentinel-nacos-demo
spring:
application:
name: sentinel-nacos-demo
profiles:
active: local
cloud:
nacos:
config:
server-addr: xxx.xxx.xx.x:8848
#server-addr: xxx.xxx.xx.x:8848
group: ${spring.application.name}
file-extension: yaml
# The configuration center uses a separate namespace
namespace: "study"
discovery:
server-addr: xxx.xxx.xx.x:8848
namespace: "study"
group: "sentinel-nocas-demo"
sentinel:
transport:
dashboard: xxx.xxx.xx.x:8842 # After starting this project, you need to request once to sentinel Console registration
port: 8719 # When a server deploys multiple applications, it needs to be configured differently port, A single application can be ignored
client-ip: 10.32.4.230 # Specify native ip Address , Avoid multiple virtual addresses , Leading to data acquisition failure
datasource:
## Configure process control
## rule-type Configure the rules that represent the type of rules in the data source (flow Flow control ,degrade Fusing the drop ,authority to grant authorization ,system System protection , param-flow Hot spot parameter current limiting , gw-flow, gw-api-group)
flow:
nacos:
server-addr: xxx.xxx.xx.x:8848
namespace: "study"
data-id: ${spring.application.name}-sentinel-flow-rules
group-id: sentinel-group
data-type: json
rule-type: flow
## Configure degradation rules
degrade:
nacos:
server-addr: xxx.xxx.xx.x:8848
namespace: "study"
dataId: ${spring.application.name}-sentinel-degrade-rules
groupId: sentinel-group
data-type: json
rule-type: degrade
system:
nacos:
server-addr: xxx.xxx.xx.x:8848
namespace: "study"
dataId: ${spring.application.name}-sentinel-system-rules
groupId: sentinel-group
data-type: json
rule-type: system
2.3 Rule configuration

Sentinel Flow control rule configuration
[
{
"resource": "/sentinel/rule/flow",
"limitApp": "default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
Sentinel Fuse rule configuration
[
{
"resource": "/sentinel/rule/degrade",
"count": 1,
"grade": 0,
"timeWindow": 10,
"minRequestAmount": 1,
"statIntervalMs": 1000,
"slowRatioThreshold": 0.1
}
]
Sentinel System protection rule configuration
[
{
"avgRt":1,
"highestCpuUsage":-1,
"highestSystemLoad":-1,
"maxThread":-1,
"qps":1000
}
]
2.4 Uniform interception rules

@Component
public static class MyBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
//Sentinel Details of the rule
BaseResponse r = BaseResponse.error("sentinel- Control interception ");
if (e instanceof FlowException) {
r = BaseResponse.error(" The interface is current limited ",e.toString());
} else if (e instanceof DegradeException) {
r = BaseResponse.error( " The service has been downgraded ",e.toString());
} else if (e instanceof ParamFlowException) {
r = BaseResponse.error(" Hot spot parameters are limited ",e.toString());
} else if (e instanceof SystemBlockException) {
r = BaseResponse.error( " Triggered the system protection rules ",e.toString());
} else if (e instanceof AuthorityException) {
r = BaseResponse.error( " Authorization rules don't pass ",e.toString());
}
// return json data
response.setStatus(500);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getWriter(), r);
}
}
3. Example of project operation
3.1 Rule interception test
Sentinel Flow control rule test

Sentinel Fusing rule test

Sentinel System protection rule test

3.2 Sentinel Console interface display
Real-time monitoring

Cluster link

Flow control rules

4. Console data display problem
4.1 Cluster link data is empty
sentinel:
transport:
dashboard: xxx.168.16.13:8842 # After starting this project, you need to request once to sentinel Console registration
port: 8719 # When a server deploys multiple applications, it needs to be configured differently port, A single application can be ignored
client-ip: xx.xx.4.230 # Specify native ip Address , Avoid multiple virtual addresses , Leading to data acquisition failure
4.2 The real-time monitoring data is empty
5.Sentinel Console and Nacos Configuration center data consistency problem
- The project team uniformly stipulates , Rule information can only be based on Nacos To configure , stay Nacos Make modifications and adjustments , Don't be in Sentinel Console operation rule information .
- Refer to some current synchronization schemes , modify Sentinel Source code , Support changing rule information on the console , Synchronize to Nacos in . For details, please refer to 《SpringBoot Sentinel Nacos (- Two way synchronization of rules - Custom response 》
6.Sentinel Some core source code analysis
ProcessorSlot
As SPI Interface expansion , bring Slot Chain With the ability to expand . Developers can add customized slot And choreograph slot Execution sequence between , So that we can give Sentinel Add custom features . 
6.1 Default slot Execution order


1. Define the loading order of implementation classes
@Spi(isSingleton = false, order = Constants.ORDER_NODE_SELECTOR_SLOT) 2. Definition NodeSelectorSlot The implementation class inherits from the abstract class
public class NodeSelectorSlot extends AbstractLinkedProcessorSlot<Object> 3. Define abstract classes to implement interfaces
public abstract class AbstractLinkedProcessorSlot<T> implements ProcessorSlot<T> 4. Define the top-level interface of the link
public interface ProcessorSlot<T>
6.2 Build default responsibility chain
ProcessorSlot
Interface , It cannot be added to the responsibility link . Reference source code : public class DefaultSlotChainBuilder implements SlotChainBuilder { @Override
public ProcessorSlotChain build() {
ProcessorSlotChain chain = new DefaultProcessorSlotChain(); List<ProcessorSlot> sortedSlotList = SpiLoader.of(ProcessorSlot.class).loadInstanceListSorted();
for (ProcessorSlot slot : sortedSlotList) {
if (!(slot instanceof AbstractLinkedProcessorSlot)) {
RecordLog.warn("The ProcessorSlot(" + slot.getClass().getCanonicalName() + ") is not an instance of AbstractLinkedProcessorSlot, can't be added into ProcessorSlotChain");
continue;
} chain.addLast((AbstractLinkedProcessorSlot<?>) slot);
} return chain;
}
}
public abstract class ProcessorSlotChain extends AbstractLinkedProcessorSlot<Object> { /**
* Add a processor to the head of this slot chain.
*
* @param protocolProcessor processor to be added.
*/
public abstract void addFirst(AbstractLinkedProcessorSlot<?> protocolProcessor); /**
* Add a processor to the tail of this slot chain.
*
* @param protocolProcessor processor to be added.
*/
public abstract void addLast(AbstractLinkedProcessorSlot<?> protocolProcessor);
}
6.3 Process summary
- Using the chain of responsibility model to complete Sentinel Information statistics of 、 Fuse 、 Current limiting and other operations ;
- In the chain of responsibility NodeSelectSlot Responsible for selecting the current resource Node, At the same time build node Call tree ;
- In the chain of responsibility ClusterBuilderSlot Currently responsible for building Node Corresponding ClusterNode, Used to aggregate the same resource corresponding to different Context Of Node;
- In the chain of responsibility StatisticSlot It is used to count the call status of the current resource , to update Node It's not the right thing to use ClusterNode All kinds of Statistics ;
- In the chain of responsibility FlowSlot Based on the current Node Corresponding ClusterNode( Default ) The statistical flow limit of information ;
- Resource call statistics ( for example PassQps) Use the sliding time window for statistics ;
- After all the work has been done , Execute the exit process , Add some statistics , clear Context.
6.4 Write a custom intercept Slot
/**
* Write a custom current limiting link
*
* @author wangling
* @date 2022/07/05
*/
@Spi(order = -3000)
public class TestMySlot extends AbstractLinkedProcessorSlot<DefaultNode> { @Override
public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode obj, int count, boolean prioritized, Object... args)
throws Throwable {
try {
fireEntry(context, resourceWrapper, obj, count, prioritized, args);
throw new BusinessException("TestMySlot- test ");
} catch (Exception e) {
throw e;
} catch (Throwable e) {
RecordLog.warn("Unexpected entry exception", e);
} } @Override
public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
try {
fireExit(context, resourceWrapper, count, args);
} catch (Throwable e) {
RecordLog.warn("Unexpected entry exit exception", e);
}
}
}

Sentinel- More related articles about traffic guard
- alibaba/Sentinel Distributed System traffic guard
Sentinel: Traffic guard of distributed system Sentinel What is it? ? With the popularity of microservices , Stability between services and services is becoming more and more important .Sentinel Take flow as the starting point , Slave flow control . Fusing the drop . System load protection, etc ...
- Spring Cloud Alibaba | Sentinel: Traffic guard of distributed system
Catalog Spring Cloud Alibaba | Sentinel: Traffic guard of distributed system 1. Sentinel What is it? ? 2. Sentinel Characteristics of : 3. Sentinel Open source students ...
- Spring Cloud Alibaba | Sentinel: Distributed system traffic guard basic combat
Spring Cloud Alibaba | Sentinel: Distributed system traffic guard basic combat Springboot: 2.1.8.RELEASE SpringCloud: Greenwich.SR2 ...
- Spring Cloud Alibaba | Sentinel: Advanced practical combat of traffic guard in distributed system
Spring Cloud Alibaba | Sentinel: Advanced practical combat of traffic guard in distributed system Before reading this article , Suggest reading first <Spring Cloud Alibaba | Sentinel: Distributed systems ...
- Spring Cloud Alibaba | Sentinel: Flow guard dynamic current limit rules of distributed system
Spring Cloud Alibaba | Sentinel: Flow guard dynamic current limit rules of distributed system The previous several articles introduced in detail Sentinel Using posture of , For those who haven't seen it, please visit the following links : &l ...
- Sentinel: Traffic guard of distributed system
Preface stay Spring Cloud In the system , We will use Hystrix frame , Current limiting usually occurs at Zuul Intermediate processing ,Zuul There is no built-in current limiting function in the , We can do our own current limiting or integrate the third-party open source current limiting framework ...
- Sentinel Traffic guard of distributed system
Sentinel What is it? ? Official website :https://github.com/alibaba/Sentinel/wiki/ Introduce With the popularity of microservices , Stability between services and services is becoming more and more important .Sentinel With the flow of ...
- 🏆【Alibaba Middleware technology series 】「Sentinel Technical topics 」 Basic introduction of traffic guard of distributed system ( Introduction to entry source code )
Recommended information Official documents official demo Sentinel What is it? ? With the popularity of microservices , Stability between services and services is becoming more and more important .Sentinel Take flow as the starting point , Slave flow control . Fusing the drop . System load protection and other multi-dimensional protection ...
- SpringCloud Alibaba ( 3、 ... and ):Sentinel Flow control unit
SpringCloud Alibaba ( 3、 ... and ):Sentinel Flow control unit Sentinel What is it? With the popularity of microservices , Stability between services and services is becoming more and more important .Sentinel It is a distributed service oriented architecture ...
- Sentinel Flow control rules
Above Sentinel The traffic guard talked about Sentinel Introduction and flow control rules are a small part , and Sentinel There are also the following rules : Fusing degradation rules Hot spot parameter rules System rules Black and white list rules This article is about flow control rules Flow control gauge ...
Random recommendation
- JNI Common mistakes
ndk Common development errors 1. android.mk file does not exist $ ndk-buildAndroid NDK: Your APP_BUILD_SCRIPT points to an unknown file: ...
- Android Alipay packaging class
Today I will introduce you to android How to integrate Alipay payment to its own APP In the middle . Give Way APP Can have convenient , Fast payment function . We're doing it Android Alipay will be paid when it is paid. , According to the official demo It's very hard to do , the ...
- php empty() and isset() The difference between
In the use of php When writing a page program , I often use variable handlers to judge php Whether a variable value of the parameter at the end of the page is empty , At first I was used to using empty() function , But found some problems , So use isset() function , ask ...
- HTML5 The main points of ( Two )
<p> <b> Today Monday </b>,<span> Ha ha ha ha ...</span> </p> <i> Italics </i&g ...
- About this A little summary of
about this Now there are a few little understandings ①this Point to the element that called it . Who calls it , Who it points to . ② Can pass call() and apply() change this The direction of ③setInterval and setTimeout Medium th ...
- Ninject Tour 12 :Ninject stay Windows Form Application on the program ( Download with program )
Abstract : The following articles describe how to use Ninject Create different types of applications . Include : Windows Form Application system ASP.NET MVC Application system ASP.NET Web Form Application system Although for different ...
- Python A collection of regular expression usage problems
In regular expressions , If the characters are given directly , It's the exact match . use \d Can match a number ,\w Can match a letter or number , therefore : '00\d' Can match '007', But it doesn't match '00A': And it can't match '1001', The effect is similar to ...
- Python3.6 Next use session session Stay logged in
This tool mainly uses python easygui Modular inputbox Let users input login information for the first time , As a website requests-post Requested data Field , Observe XHR( Load asynchronously ) Data packets of , structure post request , utilize r ...
- hdu 2647 ( A topological sort Template for adjacency table drawing ) Reward
Topic link http://acm.hdu.edu.cn/showproblem.php?pid=2647 The boss pays the employees , Everyone's basic salary is 888, And then there's the bonus , Then there are contradictions between employees , Some employees want to be better than others ...
- AngularJS+ThinkPHP Example tutorial
General idea thinkphp adopt RESTful Provide data to angular, front end ( Including template pages ) All by angular To take over . Example Implement a user management module , Add, delete, change and check through 4 Operations , With this example , Show me how to th ...