Hou Yi reproduced please note the original source, thank you!
series
Sentinel principle – Full resolution
Sentinel principle – Call chain
Sentinel Principle – Sliding Windows
Sentinel Principle – Entity classes
Sentinel Combat – Console chapter
Sentinel Combat – Rule Persistence
We already know the three main functions of Sentinel: current limiting degradation system protection. Now let’s take a look at the specific use method, to limit the flow to demonstrate the specific steps.
Introduction of depend on
The first step is to introduce the required dependencies, as follows:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>x.y.z</version>
</dependency>
Copy the code
Here, the version number X.Y.Z is optional, but I chose the latest version so far: 1.4.0.
Define the resources
Suppose we have a UserService:
public class UserService {
/** * Get user information based on uid *@param uid uid
* @returnUser information */
public User getUser(Long uid){
// Business code
User user = new User();
user.setUid(uid);
user.setName("user-" + uid);
return user;
}
public static class User {
private Long uid;
private String name;
// omit the getter and setter}}Copy the code
Now we need to limit the flow of the getUser method, so first we need to define a resource. In Sentinel, resources are abstracted to do specific operations, using resources to protect our code and service.
The user only needs to define a resource for the protected code or service, then define the rules, and Sentinel takes care of the rest. Once you have defined resources, you can protect your own services by burying them in two ways: throwing exceptions and returning booleans.
Here I throw an exception to bury the point:
// Define a resource
public static final String USER_RES = "userResource";
public User getUser(Long uid){
Entry entry = null;
try {
// Flow control code
entry = SphU.entry(USER_RES);
// Business code
User user = new User();
user.setUid(uid);
user.setName("user-" + uid);
return user;
}catch(BlockException e){
// The current is restricted
System.out.println("[getUser] has been protected! Time="+System.currentTimeMillis());
}finally {
if(entry! =null){ entry.exit(); }}return null;
}
Copy the code
In addition to defining a resource by running an exception, the way to return a Boolean value is the same, which is not expanded here.
PS: If you don’t want to intrude on the existing business code, you can also make annotations to SentinelResource.
Define the rules
After defining resources, we can define flow limiting rules. However, we need to have a detailed understanding of flow control rules to better perform flow limiting operations. Flow control rules correspond to FlowRule.
A FlowRule consists of the following important properties:
- Resource: indicates the resource name of the rule
- Grade: Indicates the type of traffic limiting threshold, QPS or number of threads
- Count: indicates the traffic limiting threshold
- LimitApp: a set of applications separated by commas when authorized, and a single application when traffic limiting
- Strategy: Traffic control based on invocation relationship
- ControlBehavior: flow control policy
The first three attributes are easier to understand and the last three are harder to understand. Let’s look at the last three attributes in detail:
limitApp
LimitApp first let’s take a look at limitApp, which literally means which application is to be restricted, mainly for traffic control based on the caller.
He has three options:
- default
Indicates that callers are not discriminated, and traffic limiting statistics are applied to requests from any callers.
- {some_origin_name}
Indicates that for a particular caller, only requests from this caller are controlled.
For example, resource NodeA is configured with a rule for caller Caller1, so traffic control is triggered if and only if requests from Caller1 to NodeA come in.
- other
To control the flow of all callers except {some_origin_name}.
For example, if resource NodeA is configured with a traffic limiting rule for caller1 and a rule for other, all calls from non-caller1 on NodeA cannot exceed the threshold defined by other.
strategy
For flow control based on call relationships, there are also three options:
- STRATEGY_DIRECT
Limiting traffic by caller. The origin parameter in the contextutil.Enter (resourceName, Origin) method identifies the caller.
If DIRECT is selected for strategy, traffic control needs to be carried out according to the limitApp field in the traffic limiting rule for callers in different scenarios, including: All callers, Origin for specific callers, and Callers except Origin for specific callers.
- STRATEGY_RELATE
Traffic limiting based on associated traffic. When two resources have a resource contention or dependency relationship, the two resources are associated. You can use association traffic limiting to avoid excessive resource contention.
For example, the read and write operations of the same database field compete. If the read speed is too high, the write speed will be affected, and the write speed will be affected.
For example, read_db and write_db represent database reads and writes, respectively. We can set traffic limiting rules for read_DB to achieve write priority: Set flowrule-strategy to ruleconstant. STRATEGY_RELATE and flowrule-refresource to write_db. In this way, when the write library operation is too frequent, the data read requests will be limited.
- STRATEGY_CHAIN
Traffic limiting based on the call link entry. Given that requests from Entrance1 and Entrance2 both invoke resource NodeA, Sentinel allows for limiting the flow of resources based on statistics for an entry.
For example: We can set flowrule-strategy to ruleconstant.chain, Also set flowrule-refResource to Entrance1 to indicate that only calls from Entrance1 are recorded in NodeA’s traffic limiting statistics, while calls from Entrance2 are allowed.
controlBehavior
Flow control policies are mainly specific traffic shaping and control policies after interception. Currently, there are three types of policies:
- CONTROL_BEHAVIOR_DEFAULT
Direct rejection is the default flow control mode. When QPS exceeds the threshold of any rule, a new request is immediately rejected by throwing a FlowException.
This method is suitable for situations where the processing capacity of the system is clearly known, such as when the exact water level of the system is determined by pressure measurement.
- CONTROL_BEHAVIOR_WARM_UP
This method is: queuing, also known as cold start. This method is mainly used when the system is at a low water level for a long time and the flow increases suddenly. Pulling the system to a high water level may overwhelm the system instantly.
Through the “cold start”, the flow slowly increases and gradually increases to the upper limit of the threshold within a certain period of time, giving the cold system a time to warm up and avoiding the cold system being overwhelmed.
- CONTROL_BEHAVIOR_RATE_LIMITER
This mode is: slow start, also known as uniform mode. In this way, the interval between requests is strictly controlled, that is, requests are passed at an even speed, corresponding to the leak-bucket algorithm.
This approach is mainly used to deal with intermittent bursts of traffic, such as message queues. Imagine a scenario where a large number of requests arrive in one second and then sit idle for a few seconds. We want the system to process these requests gradually during the rest of the idle period, rather than simply rejecting the extra requests in the first second.
The specific FlowRule can be represented in the following figure:
After the rules are defined and the application is started, our business code will be automatically protected. Of course, it is impossible to define rules by hard coding in the actual production environment. Sentinel provides a DataSource interface for us, through which we can customize the storage DataSource of the rules.
There are several ways to persist rules through the DataSource interface, for example:
- Integrate dynamic configuration systems, such as ZooKeeper and Nacos, to dynamically update configuration rules in real time
- This rule is implemented in combination with RDBMS, NoSQL, VCS, etc
- Used with Sentinel Dashboard
This article does not make a specific introduction to the persistence of rules, this article is mainly to achieve a simple flow limiting example access.
The PS: DateSource interface has been split into ReadableDataSource and WritableDataSource interfaces in the future.
See the log
We start with a Spring Boot project, where UserService is a specific service in a project. Once the project is started, ${date} ${record. Log.${date} ${userhome}/logs/ CSP /
In addition to the Sentinel-Record file, there is also a sentinel-exception file, which records the exceptions that occur during the operation of Sentinel.
Let’s open the sentinel-record.log.2019-01-02.0 file to see the details:
The sentinel-record log will record the loaded rules and other information. The specific real-time statistics log will be stored in another file called xx-metrics.log.${date}.
Viewing statistical Effect
The first step is to access our service and generate specific statistics files after the sentinel traffic limiting rules are triggered.
Now let’s take a look at the statistics file generated under ~/logs/ CSP /, as shown below:
${appName}-metrics.log.${date} ${appName} will obtain the value of the system parameter project. This is done in the AppNameUtil class.
We open the lememo-Retircs file and see the following information:
Can see we request many times after the resource, the sentinel statistics are printed out per second, with | to separate different parameters, a total of eight parameters, from left to right are:
As you can see, all of our requests have passed successfully. Now let’s change the count threshold set in the rule to 1, restart the service, request the service again, and open the lememo-Metrics file again, as shown below:
You can see that only 1 request per second passes, and the rest are blocked. Look at the log we printed in the code:
This article uses an example to practice the flow limiting of Sentinel, understand the role of the rules in detail, and also know that sentinel printed logs can be used to check the status during operation.
But this approach is more primitive. Whether it’s creating rules or viewing logs, I’ll walk you through the sentinel console in the next article.
For more original articles, please pay attention to the public account “Hou Yi Code by Code”