directory
-
I. Sentinel concept
- 1. What is Sentinel?
- 2. Sentinel features
- 3. Sentinel VS Hystrix
-
Docker deploys Sentinel Dashboard
- 1. Pull the mirror
- 2. Start the container
- 3. Access tests
-
Sentinel gateway flow control
- 1. Gateway flow control definition
- 2. Gateway flow control rules
- 3. Import dependencies
- 4. Configure the gateway
- 5. Identifies the gateway flow control client
- 6. Test requirement formulation
- 7. Nacos Add the gateway flow control rule
- 8. Gateway flow control test
- 9. The flow control of the user-defined gateway is abnormal
-
4. Sentinel Common flow control
- 1. Common flow control definition
- 2. Rules for common flow control
- 3. Import dependencies
- 4. Configure microservices
- 5. Add flow control rules to Nacos
- 6. General flow control test
- 7. Customize exceptions
-
5. Sentinel fuse downgrade
- 1. Overview of fuse downgrading
- 2. Circuit breaker policy
- 3. Fuse downgrading rules
- 4. Configure microservices
- 5. Nacos added fuse downgrading rules
- 6. Abnormal simulation of fusing
- 7. Fuse downgrade test
-
Sentinel integrates Feign fuse downgrading
- 1. Integration significance of Feign and Sentinel
- 2. Import dependencies
- 3. Configure microservices
- 4. Fuse downgrading rules
- 5. Fuse downgrade test
-
7. Conclusion
-
Eight. The appendix
I. Sentinel concept
1. What is Sentinel?
Sentinel is a lightweight high-availability flow control component developed by Ali middleware team for distributed service architecture. It mainly takes traffic as the entry point and helps developers guarantee the stability of micro-services from multiple dimensions such as flow limiting, traffic shaping, fuse downgrading, system load protection and hotspot protection. It was born in 2012 and developed rapidly within Alibaba Group and became a basic technology module covering all core scenarios. Sentinel has thus accumulated a large number of traffic integration scenarios and production practices. It was finally made open source in July 2018.
Basic concepts of Sentinel:
- Resources: The key concept of Sentinel, which can be anything in a Java application, can be protected by Sentinel using code defined by the Sentinel API. In most cases, method signatures, urls, and even service names can be used as resource names
- Rules: Rules set around the real-time status of resources, including flow control rules, circuit breaker degradation rules, and system protection rules. All rules can be dynamically adjusted in real time.
Sentinel is divided into two parts:
- The Console (Dashboard) is based on Spring Boot and can be packaged to run directly without the need for additional application containers such as Tomcat, namely sentinel-Dashboard-1.8.1.jar.
- The core library (Java client) is independent of any framework/library, can run in all Java runtime environments, and has good support for frameworks such as Dubbo/Spring Cloud.
2. Sentinel features
It can be seen from the figure above that Sentinel has many functions and features and has a wide range of application scenarios. The following is a brief description of common functions and features such as current limiting and fuse downgrading and their significance
Traffic limiting: Traffic limiting is also called traffic control. It monitors the QPS or concurrent threads of application traffic and controls the traffic when it reaches a specified threshold to avoid being overwhelmed by instantaneous traffic peaks and ensure high availability of applications.
Fuse downgrading: In addition to flow control, the timely fusing of unstable elements in the call link is one of Sentinel’s missions. Because of the complexity of the invocation relationship, if a resource in the invocation link is unstable, requests will eventually pile up, leading to cascading errors. Sentinel When a resource is detected to have unstable performance (long request response time or high abnormal ratio) in the invocation link, the Sentinel restricts the invocation of this resource to make the request fail quickly and avoid cascading faults caused by other resources.
- Fusing: Deny traffic access and turn off the fusing when the system returns to normal.
- Demote: Demote secondary services, stop services, and release system resources to core functions
3. Sentinel VS Hystrix
The following is excerpted from the Sentinel official documentation. For details, see Sentinel vs. Hystrix
Sentinel | Hystrix | |
---|---|---|
Isolation strategy | Semaphore isolation | Thread pool isolation/semaphore isolation |
Fuse downgrading strategy | Based on response time or failure rate | Based on failure ratio |
Real-time indicator realization | Sliding window | Sliding Windows (based on RxJava) |
Rule configuration | Support for multiple data sources | Support for multiple data sources |
scalability | Multiple extension points | Plug-in form |
Annotation-based support | support | support |
Current limiting | Based on QPS, traffic limiting based on call relationships is supported | Limited support |
Traffic shaping | Support slow start and constant speed mode | Does not support |
System load protection | support | Does not support |
The console | Out of the box, you can configure rules, view second-level monitoring, machine discovery, etc | imperfect |
Common framework adaptation | Servlet, Spring Cloud, Dubbo, gRPC, etc | Servlet, Spring Cloud Netflix |
Sentinel and Hystrix share the same principles, but Sentinel and Hystrix take completely different approaches to their limitations.
- Hystrix:Thread pool isolation is used to isolate dependencies (corresponding to the Sentinel concept
resources
) were quarantined. The advantage is the maximum isolation between resources, but the disadvantage is that in addition to the cost of thread switching, the thread pool size needs to be allocated to each resource in advance. - Sentinel: Resource degradation by limiting the number of concurrent threads and response time.
Docker deploys Sentinel Dashboard
1. Pull the mirror
docker pull bladex/sentinel-dashboard
Copy the code
2. Start the container
docker run --name sentinel -d -p 8858:8858 -d bladex/sentinel-dashboard
Copy the code
3. Access tests
Visit: http://IP:8858
Username/password: sentinel/sentinel
Sentinel gateway flow control
1. Gateway flow control definition
Sentinel supports stream limiting for mainstream API Gataway such as Spring Cloud Gateway and Zuul. The flow control acting on the Gateway is called Gateway flow control. Please click on Gateway flow limiting to view the implementation principle.
The schematic diagram is only extracted from the official documentation here. Pay attention to the module names and a few class names mentioned in the diagram, as they all exist at the core level.
Rule types gw-flow and gw-api-group are gateway flow control rules. For details, see RuleType enumeration RuleType
/** * flow control rule */
FLOW("flow", FlowRule.class),
/** * degrade */
DEGRADE("degrade", DegradeRule.class),
/** * param flow hotspot rule */
PARAM_FLOW("param-flow", ParamFlowRule.class),
/** * system System rule */
SYSTEM("system", SystemRule.class),
/** * authority Authorization rule */
AUTHORITY("authority", AuthorityRule.class),
/** * gateway flow Gateway traffic limiting rule */
GW_FLOW("gw-flow"."com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule"),
/** * API User-defined API definition group, can be seen as some URL matching combination */
GW_API_GROUP("gw-api-group"."com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition");
Copy the code
2. Gateway flow control rules
Field | instructions | The default value |
---|---|---|
resource | Resource name, gateway route or custom API group name (note: gateway route here is not route.id, can be debugged | |
resourceMode | Stream limiting resource type, gateway route [0] or custom API group [1] (see in detailGatewayFlowRule andSentinelGatewayConstants ) |
The gateway is the route |
grade | Current limiting threshold type, QPS [1] or thread number [0] | QPS |
count | Flow limiting threshold, QPS threshold, or thread value | |
intervalSec | Statistical interval, in seconds | 1 second |
controlBehavior | Flow control effect, currently supports fast failure [0] and uniform queuing [1] | Fail fast |
burst | The number of additional requests allowed to respond to unexpected requests | |
maxQueueingTimeoutMs | The maximum queuing time in uniform queuing mode, in milliseconds, takes effect only in uniform queuing mode | |
paramItem | Parameter attribute configuration, parseStrategy: parameter extraction strategy (0: Clien IP, 1: Remote HOST, 2: Header, 3: request parameters, 4: Cookie); FieldName: If the extraction strategy is Header mode or URL parameter mode, specify the Header name or URL parameter name. Pattern: Matching pattern of parameter values. MatchStrategy: Matching strategy of parameter values, supporting exact matching, substring matching, and regular matching. |
3. Import dependencies
<! -- Sentinel Flow control, fuse downgrading
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<! -- Persisting Sentinel rules to Nacos configuration -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
Copy the code
4. Configure the gateway
The Sentinel configuration was first placed in the local Spring Boot configuration file bootstrap-dev.yml and then placed in Nacos
spring:
cloud:
nacos:
# Registry
discovery:
server-addr: http://localhost:8848
# Configuration center
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
file-extension: yaml
sentinel:
enabled: true # sentinel switch
eager: true
transport:
dashboard: localhost:8080 # Sentinel console address
client-ip: localhost
datasource:
Gw-flow is the key of the gateway traffic limiting rule
gw-flow:
nacos:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
dataId: ${spring.application.name}-gw-flow-rules Youlai-gateway-gw-flow-rules
groupId: SENTINEL_GROUP
data-type: json
rule-type: gw-flow
Gw-api-group = gW-api-group
gw-api-group:
nacos:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
dataId: ${spring.application.name}-gw-api-group-rules Youlai-gateway-gw-api-group-rules
groupId: SENTINEL_GROUP
data-type: json
rule-type: gw-api-group
Copy the code
The datasource in the configuration is explained here, because after Sentinel adds flow control rules, if the service is restarted, the previously configured rules will disappear, so the Sentinel configuration needs to be persisted. It can be seen from the above configuration that Nacos is selected. However, before adding the gateway flow control rule in Nacos, configure it after testing and confirming the requirements.
5. Identifies the gateway flow control client
There are many differences between gateway flow control and common flow control. The gateway flow control type is GW-Flow, and the common flow control type is Flow
How do I identify flow control as a gateway type?
Many blog posts do not focus on this point, because the gateway flow control panel is not consistent with the normal flow control panel. Finally, we found this switch in the Sentinel official documentation, which is required to add JVM startup parameters to the Youlai-gateway gateway application.
# Note: This parameter is not required for API Gateway integration through Spring Cloud Alibaba Sentinel automatic access
-Dcsp.sentinel.app.type=1
Copy the code
The details are as follows:
6. Test requirement formulation
With Sentinel Dashboard deployed above and Sentinel integrated by Spring Cloud Gateway, the two parts of Sentinel (console and Java client) are now ready for testing.
The following figure simply describes the process of OAuth2 authentication interface. The user requests the gateway, and the gateway (Youlai-gateway) forwards the request to the authentication center according to the identification. The authentication center (Youlai-Auth) obtains the user information of the database from the system service (Youlai-admin) and interprets the password with the user information carried in the request. If the request succeeds, the authentication center returns the token to the user.
For the above OAuth2 authentication process, a requirement is proposed:
Assuming that the QPS limit of the certification center service is 10 and the QPS limit of the system service is 5, how to achieve flow limiting control through Sentinel?
Tips: Pay attention to the red line in the figure above. Do you think the flow control of the gateway can be restricted to the system service Youlai-admin that is indirectly related to it?
7. Nacos Add the gateway flow control rule
Access the Nacos console and add the gateway flow control rule. For details, see the description of the Gateway Flow control field.
Note that the resource name resource is not the ID of the route configured in the route. Debugging when open the Sentinel SentinelGatewayFilter# filter method can see the automatically generated is fixed prefix ReactiveCompositeDiscoveryClient_ splicing application name ${spring. Application. Na Me}, so be sure to configure resource values in the configuration file according to the automatically generated rules. Enter the ID of the gateway route. Sentinel gateway flow control cannot take effect.
In the above gateway flow control rule, the QPS upper limit of Authentication center Youlai-Auth is 10, and that of system service Youlai-admin is 5.
As for why it is set in this way, there is a conjecture that needs to be verified, whether gateway flow control can only restrict directly related Youlai-auth, but not indirectly related Youlai-admin.
If the QPS passed is 10, then the gateway flow control cannot control the indirect correlation Youlai-admin. If the QPS passed is 5, then the gateway flow control can control the indirect correlation Youlai-admin.
The following figure shows the added gateway flow control rules:
After the gateway flow control rule is added to Nacos, it will be synchronized to Sentinel and checked in Sentinel console
8. Gateway flow control test
After completing the steps above, it’s time for the real test.
Adding a thread Group
Test plan (right mouse click)-> Add -> Thread (User)-> Thread Group
Because Youlai-Auth’s QPS processing is capped at 10, you can see the restricted requests if the number of threads is greater than 10
Adding an HTTP Request
OAuth2 Login thread group (right mouse click)-> Add -> Sampler ->HTTP request
The interface obtains the token through the authentication interface forwarded by the gateway to the authentication center
Add view result tree
Because we want to see the response to the request, we add the view result tree here.
OAuth2 Login thread group (right mouse click)-> Add -> Listener -> View result tree
Start the thread group test
Start the thread group with 15 authentication requests per second. Note that if the test plan has multiple thread groups, disable all thread groups except the tests.
Click the View result tree to see the status of the request
Go to the Sentinel console to view real-time monitoring
You can see 15 requests per second, because the QPS limit set by the flow control is 10, 10 passes and 5 are rejected by Sentinel.
This result also directly shows that the gateway flow control is not omnipotent, and it cannot limit the microservices of Youlai-admin indirectly related to OAuth2 authentication request, because the QPS of Youlai-Admin is set as 5 in the gateway flow control, but 10 of the whole link succeeds in the end. Since gateway flow control cannot handle such scenarios, is there another way to do it? Of course: normal flow control.
9. The flow control of the user-defined gateway is abnormal
The default exception response for Sentinel limiting above is as follows
{"code":429."message":"Blocked by Sentinel: ParamFlowException"}
Copy the code
If you want to customize the gateway flow control exception response, how do you do it?
This can be achieved by registering callbacks on the GatewayCallbackManager through the setBlockHandler method to implement custom exception responses when the request is restricted.
Custom exception code:
@PostConstruct
private void initBlockHandler(a) {
BlockRequestHandler blockRequestHandler = (exchange, t) ->
ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(ResultCode.FLOW_LIMITING.toString()));
GatewayCallbackManager.setBlockHandler(blockRequestHandler);
}
Copy the code
In JMeter, you can see that the response is abnormal according to the customized response. B0210 is an error code about system traffic limiting in the Java development manual
4. Sentinel Common flow control
1. Common flow control definition
/** * flow flow control rule, see RuleType */
FLOW("flow", FlowRule.class)
Copy the code
The flow control acting on the gateway is called gateway flow control, while the microservice flow control acting on the other side of the gateway is called ordinary flow control
In the previous chapter, it is found that gateway flow control is not omnipotent. For example, when authentication center Youlai-Auth calls system service Youlai-admin and other microservices call each other without going through the gateway, gateway flow control is powerless. However, it is undeniable that gateway flow control can indeed cope with flow control in most scenarios.
Therefore, in cases where the gateway flow control is unable to do anything, ordinary flow control needs to be saved.
2. Rules for common flow control
Field | instructions | The default value |
---|---|---|
resource | The resource name is the object of the traffic limiting rule | |
count | Current limiting threshold | |
grade | Current limiting threshold type, QPS [1] or thread count mode [0] | QPS model |
limitApp | The source of the call for flow control | default , indicates that the call source is not distinguished |
strategy | Is the judgment based on the resource itself or on other associated resources (refResource ), or according to the link entry |
According to the resource itself |
controlBehavior | Flow control effect (Direct reject/queue wait/slow start mode) | Direct refused to |
3. Import dependencies
<! -- Sentinel Flow control, fuse downgrading
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<! -- Persisting Sentinel rules to Nacos configuration -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
Copy the code
4. Configure microservices
spring:
application:
name: youlai-admin
cloud:
nacos:
discovery:
server-addr: http://localhost:8848
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
file-extension: yaml
sentinel:
enabled: true
eager: true # Cancel console lazy loading and connect to Sentinel upon project startup
transport:
client-ip: localhost
dashboard: localhost:8080
datasource:
If you want to limit the flow of traffic, use the key "flow"
flow:
nacos:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
dataId: ${spring.application.name}-flow-rules
groupId: SENTINEL_GROUP
data-type: json
rule-type: flow
Copy the code
5. Add flow control rules to Nacos
Go to the Nacos console and add the rule configuration file. Following the example above, during authentication, youlai-auth calls Youlai-admin via feign to obtain user information based on the user name.
In addition to the rules just added in Nacos, you can also see the difference between the normal flow control panel and the gateway flow control panel
6. General flow control test
After the restriction of gateway flow control, only 10 requests can be sent to Youlai-auth, and then Youlai-auth calls Youlai-admin link. Because the QPS limit of Youlai-admin is limited to 5, only 5 requests should be valid in the end. Look at the test results:
7. Customize exceptions
The above exception information after traffic limiting is obviously not desired. Then, how to customize common flow control exceptions?
Solution: Implement the BlockExceptionHandler interface
@Component
public class DefaultBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
response.setStatus(HttpStatus.ok().status());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
if(e instanceof FlowException){
// objectMapper.writeValue is used to transpose a Java object back to the caller in JSON format
newObjectMapper().writeValue(response.getWriter(), Result.failed(ResultCode.FLOW_LIMITING)); }}}Copy the code
In order to test the common flow control, first turn off the gateway flow control to eliminate some abnormal interference
Add an HTTP request to get information about the current logged-in user
Because this HTTP interface requires authentication, you need to add a token in the request header. Right-click HTTP Request -> Add -> Configure Components ->HTTP Header Management
HTTP header manager adds tokens
Execute the thread group to see that the custom exception takes effect
5. Sentinel fuse downgrade
1. Overview of fuse downgrading
Microservice architectures are distributed. Different services call each other and form complex call links. If a link in a complex link is unstable, it may cascade to make the whole link unavailable. Therefore, it is necessary to fuse downgrades unstable weakly dependent service invocations to temporarily cut off unstable invocations and avoid the avalanche of topic caused by local unstable factors. Fuse downgrading is usually configured on the client side (calling side) as a means of protecting itself.
2. Circuit breaker policy
Sentinel offers three circuit breaker strategies:
- Slow call Ratio: The request response time greater than the set RT (that is, the maximum response time) is counted as slow calls. Two conditions must be met to trigger the fuse breaker policy. One is that the number of requests per statIntervalMs is greater than the set minimum number of requests; the other is that the ratio of slow calls is greater than the threshold. Then the requests are automatically fused within the fuse breaker duration. After the fuse duration expires, the fuse enters the half-open state. If the response time of the next request is less than the set slow-call RT, the fuse ends. If the response time is longer than the set slow-call RT, the fuse will be fused again.
- Abnormal ratio: When the number of requests per unit statistical period is greater than the minimum number of requests and the proportion of abnormal requests is greater than the threshold, the requests will be automatically fused within the following fuse duration.
- Number of exceptions: When the number of exceptions in a unit statistics period exceeds the threshold, the circuit breaker is automatically disabled.
3. Fuse downgrading rules
A fuse DegradeRule contains the following important properties:
Field | instructions | The default value |
---|---|---|
resource | The resource name, which is the object of the rule | |
grade | Fuse breaker policy: supports the ratio of slow calls, ratio of exceptions, and number of exceptions policies | Slow call ratio |
count | In slow call ratio mode, it is slow call critical RT (beyond this value, it is slow call); In exception ratio/Number of exceptions mode, the corresponding threshold is set | |
timeWindow | Fusing duration, unit: s | |
minRequestAmount | Minimum number of requests triggered by fuses. If the number of requests is less than this value, fuses will not be triggered even if the abnormal ratio exceeds the threshold (introduced in 1.7.0) | 5 |
statIntervalMs | Statistical duration (unit: ms), for example, 60*1000 represents minute level (introduced in 1.8.0) | 1000 ms |
slowRatioThreshold | Slow call ratio threshold, valid only for slow call ratio mode (introduced in 1.8.0) |
4. Configure microservices
spring:
cloud:
sentinel:
They don't degrade themselves by degrade themselves
degrade:
nacos:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
dataId: ${spring.application.name}-degrade-rules
groupId: SENTINEL_GROUP
data-type: json
rule-type: degrade
Copy the code
5. Nacos added fuse downgrading rules
Convenient to see the effect of abnormal circuit breaker, choose the abnormal number of circuit breaker strategy, after all, counting is much easier than calculating the proportion. The resource name getCurrentUser will not be mentioned below. For getCurrentUser, if an exception occurs on the request interface, a fuse will be run for 5 seconds.
6. Abnormal simulation of fusing
To simulate a run-time exception, make a landmine on the interface that gets the information about the currently logged user. Note the @SentinelResource annotation value getCurrentUser, which is the name of the resource. Instead of using the requested path in the normal flow control test above, it shows the resource name specified and the degrade rule configured to do the matching.
In addition to the attribute value that defines the resource name, the attributes in the @SentinelResource annotation are blockHandlerClass and blockHandler. When the number of interface exceptions per unit time exceeds the set threshold, the interface is fusible. Within the fusible duration (5 seconds is set in the above degradation rule), the logic in the interface method will not be used for any more requests to access the interface. Because the first several times the interface is abnormal, then dare to conclude that the next short period of time will be a large probability of abnormal, so simply to the follow-up request interception to avoid, this is also the meaning of the circuit breaker.
Within 5 seconds of fusing time, if have any request to access the interface will go down logic, which is above the specified UserBlockHandler# handleGetCurrentUserBlock degradation process.
7. Fuse downgrade test
Before the test, it is necessary to turn off the flow control on the gateway side to eliminate some interference under abnormal conditions. Also, temporarily shut down the GlobalExceptionHandler GlobalExceptionHandler to facilitate viewing the results in JMeter.
Take the thread group configured in the section to test common flow control and obtain the information of the logged-in user as the test case of fuse degradation. Let’s take a look at the Settings of the thread group:
The number of threads is 10, which meets the minimum number of fusible downgrade requests (5 in the rule configuration)
Interface information to get login user information
Request header adds token
After testing the thread group configuration, see the difference between using fuse degrade without and with fuse degrade:
- Do not use fuse downgrades
Disable Sentinel in configuration
sentinel:
enabled: false
Copy the code
Do you see that? This request exception processing mode head iron ah, even if hit the south wall will not look back, next time continue to hit, next time continue to hit. Ok, you never mind, that you have to consider the wall (server) you have been hit?
- Use fuse downgrades
The Sentinel function is enabled
sentinel:
enabled: true
Copy the code
You can see from the log that the mainline code is only entered once, and subsequent requests go directly to the degraded branch.
After the fuse duration is 5 seconds, the fuse enters the half-open state. At this time, if a request reaches the main line properly, the fuse is closed and the subsequent requests are sent to the main line. If the fault persists, turn on the fuse.
Sentinel integrates Feign fuse downgrading
1. Integration significance of Feign and Sentinel
In microservice architecture, declarative invocation of Feign plays an important role in the invocation between microservices. In the process of using Feign, for the sake of system robustness, it must be considered if the invocation fails due to the target service exception.
For those of you who know something about microservices, the following code is familiar:
The above two figures reflect the Feign client’s failure to call the target service remotely, and then choose to degrade the logic, like a human being, always leave a backdoor, namely stability, refraction to the program is the same. This is just a degraded custom exception return, depending on the business.
Seeing the code above, Feign is designed to support degradation handling. Feign already supports downgrading, so why Sentinel?
In other words, it might be a little bit easier to understand, what does Sentinel do for Feign?
This question is actually not difficult to understand, first cut directly from the literal.
Feign can be downgraded, Sentinel can be circuit breaker downgraded, which stands out as the term circuit breaker, what is the representation of circuit breaker? Here’s an example:
If client A invokes service B 100 times through feign, service B fails
-
There is no fuse
The first request of A goes to service B, sees service B lying on the ground and does not move, and responds to client A that service B does not move and lets client A deal with it by itself. This is repeated 99 times. Each time, CLIENT A needs to walk to client B and then respond to client A, telling client B that it is faulty.
-
A fuse
A first approached b service request, looking at b lying on the ground have no action, this time a it more tactful, judge b service no moment is not coming at the moment, is the response to the client a and said this for a quarter of an hour’s request yourself looking at processing, there is no need to b in front, behind the 99 requests will not come again to service b, save time and effort.
The above examples illustrate the significance and function of the circuit breaker. Since Feign already supports downgrading, it would be like adding a tiger’s wings to the Sentinel circuit breaker.
Next, through the example of the previous project, the authentication center [Youlai-Auth] requires remote Feign to call the system service [Youlai-admin] to obtain user information according to the user name when logging in, to illustrate how Sentinel integrates Feign to achieve fusible degrade and its charm.
2. Import dependencies
Youlai-auth adds Sentinel and Nacos persistence rule dependencies
<! -- Sentinel Flow control, fuse downgrading
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<! -- Persisting Sentinel rules to Nacos configuration -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
Copy the code
3. Configure microservices
Youlai-auth turned on Feign support for Sentinel
spring:
application:
name: youlai-auth
cloud:
sentinel:
enabled: true
eager: true # Cancel console lazy loading and connect to Sentinel upon project startup
transport:
client-ip: localhost
dashboard: localhost:8080
datasource:
# Demotion rule
degrade:
nacos:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
dataId: ${spring.application.name}-degrade-rules
groupId: SENTINEL_GROUP
data-type: json
rule-type: degrade
# Feign Enable Sentinel support
feign:
sentinel:
enabled: true
Copy the code
4. Fuse downgrading rules
Add the Demotion rule for Youlai-Auth to the Nacos console
[{"resource": "GET:http://youlai-admin/api.admin/v1/users/username/{username}"."grade": 2."count": 1."timeWindow": 5}]Copy the code
Note the resource name generation rule. The configuration above means that if there is one exception per unit of time, there is no request within the next 5 second window because the fuse is on and the request goes directly to the degrade logic.
5. Fuse downgrade test
Firstly, the interface abnormality of obtaining user information according to user name of system service should be simulated, as shown in the following figure:
Configure the JMeter thread group to execute 10 requests within 1s. The specific configuration is described in common flow control and will not be described here.
It turns out that 10 requests were actually executed at Youlai-Auth, because the target service’s exception followed the logic of degradation
However, the interface method of obtaining user information by user name entered into Youlai-admin only once, and the subsequent 9 requests directly followed the degradation logic of Feign client
The above test results confirm that Feign’s integration with Sentinel has achieved the circuit breaker and downgrade, so Feign is no longer alone.
7. Conclusion
In this paper, the flow control and fuse downgrading of Sentinel are verified one by one. Gateway flow control and general flow control can ensure the stable operation of the system with limited resource capacity, and fusible degrade can provide last-resort processing logic to ensure the robustness of the system in case of system failure. Feign that supports degraded Feign can integrate Sentinel and get the fusible degrade skills, so fusible degrade combines both of them.
In the past, I thought the flow limiting and circuit breaker degradation of micro-services were dispensable, so I have not been doing relevant integration in the open source project. When I really understand the interests of micro-services, they cannot do without them.
Of course, the Sentinel function mentioned in this article is the tip of the iceberg, such as the extension of traffic limiting, hotspot key, IP traffic limiting, parameter traffic limiting, etc. The specific choice of use depends on the scene, the function is rich, there is always something you need. And easy to use, is a very good framework, the internal implementation principle and algorithm is necessary to understand further.
If you have any questions, please add me on wechat (wechat id: HaoxianRUI)
Eight. The appendix
Source code address:
platform | address |
---|---|
github | Github.com/hxrui/youla… |
gitee | Gitee.com/youlaitech/… |
The Sentinel rule configuration in this article has been placed in the project Document/NACOS/sentinel_group.zip and can be imported into the NACOS console
Of course, you can also start the Sentinel local console, has placed the official jar packages in the project youlai – middleware/setinel/Sentinel – dashboard -, version 1.8.1. Jar
cdYoulai - middleware/setinel Java - jar sentinel - dashboard -, version 1.8.1. JarCopy the code
To access the Sentinel console, visit http://localhost:8080 locally
Welcome to join the open source project exchange group and participate in the development of open source projects.