🔰 Learning video 🔰
Number of episodes: 111-137
🔰 Learning maxims 🔰
Not knowing, but doing.
🔰 Study notes 🔰
[Java] summary of learning notes
🔰 Project address 🔰
https://gitee.com/zqcliudaliuda/cloud2021
1, Introduction
Introduction to github,Introduction to Spring official website
Sentinel: traffic guard of distributed system
With the popularity of microservices, the stability between services and services becomes more and more important. Sentinel takes traffic as the starting point to protect the stability of services from multiple dimensions such as traffic control, fuse degradation and system load protection.
Sentinel has the following characteristics:
- Rich application scenarios: Sentinel has undertaken the core scenarios of Alibaba's double 11 traffic promotion in recent 10 years, such as second kill (i.e. sudden traffic control within the range of system capacity), message peak cutting and valley filling, cluster traffic control, real-time fuse downstream unavailable applications, etc.
- Complete real-time monitoring: Sentinel also provides real-time monitoring function. You can see the second level data of a single machine connected to the application in the console, and even the summary operation of clusters with a scale of less than 500.
- Extensive open source Ecology: sentinel provides out of the box integration modules with other open source frameworks / libraries, such as Spring Cloud, Apache Dubbo, gRPC and Quarkus. You can quickly access sentinel by introducing corresponding dependencies and simple configuration. Sentinel also provides native implementations of Java/Go/C + + and other languages.
- Perfect SPI extension mechanism: Sentinel provides simple, easy-to-use and perfect SPI extension interface. You can quickly customize logic by implementing extension interfaces. For example, custom rule management, adapting dynamic data sources, etc.
Sentinel's main features:
Sentinel's open source ecosystem:
Sentinel is divided into two parts:
- The core library (Java client) does not rely on any framework / library and can run in all Java runtime environments. At the same time, it also has good support for frameworks such as Dubbo / Spring Cloud.
- The Dashboard is developed based on Spring Boot and can be run directly after packaging without additional application containers such as Tomcat.
2, Download and install
🔶 Download: https://github.com/alibaba/Sentinel/releases
Select version 1.7.0.
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency>
🔶 function
Ensure that java8 is successfully installed and port 8080 is not occupied.
Double click to run directly: sentinel-dashboard-1.7.0.jar
Post run access: http://localhost:8080/
The account and password are sentinel
3, Initialize demo project
3.1 new project
🔶 New maven project:
New maven project: cloudalibaba sentinel service8401
🔶 POM
<dependencies> <!-- SpringCloud alibaba sentinel--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <!-- SpringCloud alibaba nacos--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!-- SpringCloud alibaba sentinel-datasource-nacos For persistence--> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
🔶 application.yml
server: port: 8401 spring: application: name: cloudalibaba-sentinel-service cloud: nacos: discovery: server-addr: localhost:8848 sentinel: transport: dashboard: localhost:8080 # Configure sentinel dashboard address port: 8719 # The default port is 8179. If it is occupied, it will automatically scan from 8719 to + 1 until an unoccupied port is found management: endpoints: web: exposure: include: '*'
🔶 Main startup class
@SpringBootApplication @EnableDiscoveryClient @RefreshScope public class MainApp8401 { public static void main(String[] args) { SpringApplication.run(MainApp8401.class, args); } }
🔶 Business class
@RestController public class FlowLimitController { @GetMapping("/testA") public String testA() { return "------testA"; } @GetMapping("/testB") public String testB() { return "------testB"; } }
3.2 testing
Start the nacos microservice 8848 (start it on windows) and double-click to run it.
Start sentinel micro service 8080, double-click run or java -jar sentinel-dashboard-1.7.0.jar
Start microservice 8401.
Access: http://localhost:8080/
Empty, because sentinel uses the lazy loading mode, it must be accessed once.
visit: http://localhost:8401/testA
visit: http://localhost:8401/testB
4, Flow control
4.1 basic introduction
The principle of flow control is to monitor the QPS or the number of concurrent threads of application traffic, and control the traffic when the specified threshold is reached, so as to avoid being overwhelmed by the instantaneous traffic peak, so as to ensure the high availability of the application.
- Resource Name: unique name, default request path.
- For source: Sentine can limit the flow for the caller, fill in the micro service name, and default (regardless of source).
- Threshold type / single machine threshold:
- QPS (number of requests per second): limit the flow when the QPS calling the api reaches the threshold.
- Number of threads: limit the flow when the number of threads calling the api reaches the threshold.
- Cluster: no cluster is required
- Flow control mode:
- Direct: when the api reaches the current limiting condition, the current is limited directly.
- Association: when the associated resource reaches the threshold, it limits itself.
- Link: only record the traffic on the specified link (the traffic of the specified resource coming in from the entrance resource. If it reaches the threshold, limit the flow) [api level for the source]
- Flow control effect
- Quick failure: direct failure, throw exception.
- Warm Up: according to the value of codeFactor (cold loading factor, default 3), the set QPS threshold is reached after preheating time from the threshold / codeFactor.
- Queuing: queue at a constant speed to allow requests to pass at a constant speed. The threshold type must be set to QPS, otherwise it is invalid.
4.2 flow control mode
4.2.1 default direct
Add flow control for resource
Edit flow control rules once a second.
visit: http://localhost:8401/testA
If the access speed does not exceed 1 time / s, normal access; If the access speed exceeds 1 time / s, the fast fails and a default error is reported.
Blocked by Sentinel (flow limiting)
Later, you will modify the default error message and set fallback.
4.2.2 Association
When the associated resource reaches the threshold, it limits itself; When the resource B associated with A reaches the threshold, it limits the current A itself; B got into trouble, A hung up. For example, if the payment interface reaches the threshold, the current limiting order interface will be.
When the qps threshold of the associated resource / testB exceeds 1, the Rest access address of the current / testA is limited. When the associated resource reaches the threshold, the configured resource name is limited.
Simulate concurrent access using POSTMAN / testB
Create a collection and add a request to the collection.
Set 20 threads, and one thread will be sent every 0.3 seconds.
Access: http://localhost:8401/testA , A will be restricted.
4.3 flow control effect
4.3.1 fast failure
Rule constant. Control_behavior_default is the default flow control method. When the QPS exceeds the threshold of any rule, the new request will be rejected immediately. The rejection method is to throw FlowException. This method is applicable when the processing capacity of the system is exactly known, such as when the accurate water level of the system is determined through pressure measurement.
4.3.2 Warm up
Warm Up (RuleConstant.CONTROL_BEHAVIOR_WARM_UP) mode, i.e. preheating / cold start mode. When the system is at low water level for a long time and the flow increases suddenly, directly raising the system to high water level may crush the system instantly. Through "cold start", let the flow through increase slowly and gradually increase to the upper threshold within a certain time, so as to give the cold system a warm-up time to avoid the cold system being crushed.
Case: at the moment of opening the second kill system, there will be a lot of flow, which is likely to kill the system. The preheating method is to slowly put the flow in to protect the system and slowly increase the threshold to the set threshold.
Description formula: divide the threshold value by coldFactor (the default value is 3), and the threshold value will not be reached until it is preheated for a long time.
The default coldFactor is 3, that is, the required QPS starts from (threshold/ 3) and gradually rises to the set QPS threshold after the preheating time.
In case, the threshold value is 10 + preheating duration is set for 5 seconds. The threshold value of system initialization is 10 / 3, which is about 3, that is, the valve is estimated to be 3 at the beginning; Then after 5 seconds, the threshold slowly increased and recovered to 10.
Quick access: http://localhost:8401/testB
Current limiting will occur at the beginning, and will not occur slowly.
4.3.3 queuing
The uniform queuing (ruleconstant. Control_behavior_rate_limit) method will strictly control the interval between requests, that is, let requests pass at a uniform speed, corresponding to the leaky bucket algorithm.
This method is mainly used to deal with intermittent burst traffic, such as message queue. Imagine a scenario where a large number of requests arrive in one second and are idle in the next few seconds. We hope that the system can gradually process these requests during the next idle period, rather than directly reject redundant requests in the first second.
Note: the uniform queuing mode does not support QPS > 1000 for the time being.
Modify business class
@RestController @Slf4j public class FlowLimitController { @GetMapping("/testA") public String testA() { return "------testA"; } @GetMapping("/testB") public String testB() { log.info(Thread.currentThread().getName() + "\t" + "....testB"); return "------testB"; } }
Set postman
Start 8401, start postman test:
idea console output
Each response is roughly two seconds apart. Each request has a response, but it needs to wait in line.
5, Fuse degradation
5.1 general
In addition to flow control, fusing and degrading unstable resources in the call link is also one of the important measures to ensure high availability. A service often calls other modules, such as another remote service, database, or third-party API. For example, when paying, you may need to call the API provided by UnionPay remotely; To query the price of a commodity, you may need to query the database. However, the stability of this dependent service cannot be guaranteed. If the dependent service is unstable and the response time of the request becomes longer, the response time of the method calling the service will also become longer and the threads will accumulate, which may eventually deplete the thread pool of the business itself and make the service itself unavailable.
Modern microservice architectures are distributed and consist of many services. Different services call each other to form a complex call link. The above problems will produce amplification effect in link call. If a ring on a complex link is unstable, it may cascade layer by layer, resulting in the unavailability of the whole link. Therefore, we need to fuse and downgrade the unstable weak dependent service calls, temporarily cut off the unstable calls, and avoid the overall avalanche caused by local unstable factors. As a means of protecting itself, fuse degradation is usually configured at the client (caller).
5.2 degradation strategy
Sentinel will restrict the call of a resource when it is in an unstable state in the call link (for example, the call timeout or the abnormal proportion increases), so as to make the request fail quickly and avoid affecting other resources and causing cascading errors. When a resource is downgraded, calls to the resource will be automatically fused within the next downgrade time window (the default behavior is to throw DegradeException).
5.2.1 average response time RT
🔶 explain
The average response time (in seconds) exceeds the threshold and the request passed within the time window > = 5. After the two conditions are met at the same time, the circuit breaker is triggered to close after the degradation window period
RT is 4900 at most (larger ones can take effect only through dcsp.sentinel.statistical.max.rt = XXXX).
🔶 test
Add to the service class:
@GetMapping("/testD") public String testD() { try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace(); } return "------testD"; }
Configure degradation rules
Start jmeter, create a new thread group, number of threads 10, and permanent loop.
Set the ip, port number and access path and start running.
According to the above configuration, always call 10 threads (more than 5) to call testD in one second. We hope to complete this task in 200 milliseconds,
If the process is not completed for more than 200 milliseconds, the circuit breaker opens (fuse trips) the microservice is unavailable and the fuse trips and de energizes within the next 1 second time window.
5.2.2 abnormal proportion
🔶 explain
When QPS > = 5 and the abnormal proportion (second level) exceeds the threshold, degradation is triggered; When the time window is over, turn off the downgrade.
Error_ratio: when the number of requests in the unit statistical duration (statIntervalMs) is greater than the set minimum number of requests, and the proportion of exceptions is greater than the threshold, the requests in the next fusing duration will be blown automatically. After fusing for a long time, the fuse will enter the detection recovery state (HALF-OPEN state). If the next request is successfully completed (no error), the fusing will be ended, otherwise it will be blown again. The threshold range of abnormal ratio is [0.0, 1.0], representing 0% - 100%.
🔶 test
New downgrade rule
Modify business class
@GetMapping("/testD") public String testD() { // try { // TimeUnit.SECONDS.sleep(1); // } catch (Exception e) { // e.printStackTrace(); // } // System.out.println("testD"); int a = 10/0; System.out.println("Abnormal proportion testD"); return "------testD"; }
Start jmeter, create a new thread group, number of threads 10, and permanent loop.
Set the ip, port number and access path and start running.
During the test, if the configuration is successful, access http://localhost:8401/testD The following message appears:
Blocked by Sentinel (flow limiting)
According to the above configuration, if you access it alone, you must report an error once (int age = 10/0), and adjust it once and make an error once;
After jmeter is enabled, requests are sent directly with high concurrency, and multiple calls meet our configuration conditions. When the circuit breaker is opened (the fuse trips), the microservice is unavailable, and the error is no longer reported, but the service is degraded.
5.2.3 number of exceptions
🔶 explain
When the abnormal constant (minute Statistics) exceeds the threshold, the degradation is triggered; When the time window is over, turn off the downgrade.
Error_count: when the number of exceptions in the unit statistical time exceeds the threshold, it will automatically fuse. After fusing for a long time, the fuse will enter the detection recovery state (HALF-OPEN state). If the next request is successfully completed (no error), the fusing will be ended, otherwise it will be blown again.
🔶 test
Edit demotion rule
5 visits: http://localhost:8401/testD
The first five times were wrong, and the sixth time began to degrade.
6, Hot spot parameter current limiting
6.1 general
What are hot spots? Hot spots are frequently accessed data. Many times, we want to count the Top K data with the highest access frequency in a hot data and restrict its access. For example:
- Commodity ID is a parameter that counts and limits the most frequently purchased commodity ID in a period of time
- User ID is a parameter, which limits the user ID frequently accessed over a period of time
Hotspot parameter current limiting will count the hotspot parameters in the incoming parameters, and limit the current of resource calls containing hotspot parameters according to the configured current limiting threshold and mode. Hotspot parameter current limiting can be regarded as a special flow control, which is only effective for resource calls containing hotspot parameters.
Sentinel uses LRU policy to count the most frequently accessed hot spot parameters recently, and combines token bucket algorithm for parameter level flow control. Hotspot parameter current limiting supports cluster mode.
6.2 Setup Test
Added in the business class FlowLimitController:
@GetMapping("/testHotKey") @SentinelResource(value = "testHotKey", blockHandler = "deal_testHotKey") public String testHotKey(@RequestParam(value = "p1", required = false) String p1, @RequestParam(value = "p2", required = false) String p2) { return "----------testHotKey"; } public String deal_testHotKey(String p1, String p2, BlockException exception) { return "----------deal testHotKey"; // Sentinel system default promotion: Blocked by Sentinel (flow limiting) }
visit: http://localhost:8401/testHotKey or http://localhost:8401/testHotKey?p1=1&p2=2 , success:
----------testHotKey
Start 8401 microservice and add hotspot configuration rules: index 0 is for the first parameter, and the access to the index cannot exceed 1 time / s.
Quick access: http://localhost:8401/testHotKey?p1=1&p2=2
If it succeeds for the first time and more than twice a second, we will call our custom bottom method deal_ testHotKey. Because @ SentinelResource(value = "testHotKey", blockHandler = "deal_testHotKey") is set, the method of revealing the truth is selected.
If you do not configure the bottom method, an Error Page and unfriendly user prompt will appear.
Access limit: http://localhost:8401/testHotKey?p1=1&p2=2
Access limit: http://localhost:8401/testHotKey?p1=1
Unlimited number of visits: http://localhost:8401/testHotKey?p2=2
6.3 parameter exception test
Normal setting: after more than one second, the current will be limited immediately after reaching the threshold value of 1; However, we expect that when p1 parameter is a special value, its current limit is different from usual. If p1 value is equal to 5, its threshold can reach 200.
When the parameter value is 5, the current limiting threshold becomes 200 and other values are 1.
visit: http://localhost:8401/testHotKey?p1=1 , restricted
visit: http://localhost:8401/testHotKey?p1=5 , the QPS reaches 200, and no limit can be observed even if it is refreshed all the time.
🔶 be careful:
@SentinelResource: it deals with violations of Sentinel console configuration, including the details of blockHandler method configuration;
RuntimeException: int age = 10/0. This is the runtime exception runtimeException reported by java runtime.
@SentinelResource supervisor has an error in configuration and operation. This is an exception
7, System adaptive current limiting
Sentinel system's adaptive flow restriction controls the application inlet flow from the overall dimension. Combined with the monitoring indicators of application Load, CPU utilization, overall average RT, inlet QPS and the number of concurrent threads, the system inlet flow and system Load are balanced through adaptive flow control strategy, Let the system run at the maximum throughput as much as possible while ensuring the overall stability of the system.
- Load adaptation (only valid for Linux / Unix like machines): load1 of the system is used as the heuristic index for adaptive system protection. When system load1 exceeds the set heuristic value and the current number of concurrent threads exceeds the estimated system capacity, system protection will be triggered (BBR stage). The system capacity is estimated from the maxQps * minRt of the system. The setting reference value is generally CPU cores * 2.5.
- CPU usage (version 1.5.0 +): when the system CPU utilization exceeds the threshold, the system protection is triggered (value range 0.0-1.0), which is sensitive.
- Average RT: when the average RT of all inlet flows on a single machine reaches the threshold, the system protection is triggered, and the unit is milliseconds.
- Number of concurrent threads: system protection is triggered when the number of concurrent threads of all inlet traffic on a single machine reaches the threshold.
- Inlet QPS: when the QPS of all inlet flows on a single machine reaches the threshold, the system protection is triggered.
8, SentinelResource
8.1 normal conditions
Modify 8401 microservices
🔶 Add POM dependency and introduce the previously established module: cloud API Commons
<!-- Introduce customization api General package--> <dependency> <groupId>com.zqc.springcloud</groupId> <artifactId>cloud-api-commons</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
Because it contains the CommonResult class:
@Data @AllArgsConstructor @NoArgsConstructor public class CommonResult<T> { private Integer code; private String message; private T data; public CommonResult(Integer code, String message) { this(code, message, null); } }
🔶 New business class
@RestController public class RateLimitController { @GetMapping("/byResource") @SentinelResource(value = "byResource", blockHandler = "handleException") public CommonResult byResource() { return new CommonResult(200, "Current limit test by resource name ok",new Payment(2020L, "serial001")); } public CommonResult handleException(BlockException exception) { return new CommonResult(444, exception.getClass().getCanonicalName() + "\t Service Unavailable"); } }
Run microservices and access: http://localhost:8401/byResource
{"code":200,"message":"Current limit test by resource name ok","data":{"id":2020,"serial":"serial001"}}
🔶 Configuration rules
When configuring rules, you can use url(@GetMapping()) or resource name (@ SentinelResource()).
Next, flow control by resource name
More than 1 visit / s: http://localhost:8401/byResource
{"code":444,"message":"com.alibaba.csp.sentinel.slots.block.flow.FlowException\t Service Unavailable","data":null}
If the blockHandler method is not set, the current limiting processing result of Sentinel will be returned.
8.2 problems faced
- By default, the system does not reflect our own business requirements.
- According to the existing conditions, the customized processing method is coupled with the business code, which is not intuitive.
- Each business method adds a bottom-up, and the code inflation intensifies.
- The globally unified processing method is not reflected.
8.3 custom current limiting processing logic
To solve the coupling problem, put the bottom method into a single class.
🔶 Custom current limiting processing class CustomerBlockHandler
It contains two custom methods, which will be used later.
public class CustomerBlockHandler { public static CommonResult handlerException1(BlockException exception) { return new CommonResult(4444, "Customized by customer, global handlerException----------1"); } public static CommonResult handlerException2(BlockException exception) { return new CommonResult(4444, "Customized by customer, global handlerException----------2"); } }
🔶 Methods in new business classes
After limiting the flow, this method will call the handlerException2 method in the CustomerBlockHandler class.
@GetMapping("/rateLimit/customerBlockHandler") @SentinelResource( value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException2") public CommonResult customerBlockHandler() { return new CommonResult(200, "Customized by customer", new Payment(202L, "serial002")); }
visit: http://localhost:8401/rateLimit/customerBlockHandler
{"code":200,"message":"Customized by customer","data":{"id":202,"serial":"serial002"}}
🔶 Add current limiting rule
🔶 test
Visit more than 1 time / s: http://localhost:8401/rateLimit/customerBlockHandler
{"code":4444,"message":"Customized by customer, global handlerException----------2","data":null}
9, Service fuse
9.1 project testing
Create three microservices to complete the following functions. The code is in Gitee and will not be repeated here.
Test 9003 access: http://localhost:9003/paymentSQL/1
{"code":200,"message":"from mysql, serverPort: 9003","data":{"id":1,"serial":"000001"}}
Test 9004 access: http://localhost:9004/paymentSQL/1
{"code":200,"message":"from mysql, serverPort: 9004","data":{"id":1,"serial":"000001"}}
Test 84 access: http://localhost:84/consumer/fallback/1
{"code":200,"message":"from mysql, serverPort: 9003","data":{"id":1,"serial":"000001"}} Or, load balancing {"code":200,"message":"from mysql, serverPort: 9004","data":{"id":1,"serial":"000001"}}
9.2 exception handling and configuration violations
Control class:
@RestController public class CircleBreakerController { public static final String SERVICE_URL = "http://nacos-payment-provider"; @Resource private RestTemplate restTemplate; @RequestMapping("/consumer/fallback/{id}") @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler") public CommonResult<Payment> fallback(@PathVariable Long id) { CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id); if(id==4) { throw new IllegalArgumentException("IllegalAccessException, Illegal parameter exception"); } else if (result.getData() == null) { throw new NullPointerException("NullPointerException, Should id No corresponding record, null pointer exception"); } return result; } // fallback manages runtime exceptions, which is equivalent to service degradation in hystrix public CommonResult handlerFallback(@PathVariable Long id,Throwable e) { Payment payment = new Payment(id, "null"); return new CommonResult(444, "Fundus abnormality handlerFallback, exception content " + e.getMessage(), payment); } // blockHandler management configuration violation, regardless of exception public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) { Payment payment = new Payment(id, "null"); return new CommonResult(445, "blockHandler-sentinel Current limiting, No such flow: blockException " + blockException.getMessage(), payment); } }
Configure service degradation rules:
visit: http://localhost:84/consumer/fallback/4
The first two times: exception handling, calling fallback
Later: exception twice within 2m, configuration violation, call blockHandler.
9.3 ignore exceptions
fallback is no longer used for a certain type of exception.
9.4 integrating OpenFeign
🔶 POM dependency:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
🔶 In the yml configuration file, activate sentinel support for Feign
feign: sentinel: enabled: true
🔶 Add comments to the main startup class: @ EnableFeignClients
🔶 Interface + Notes:
@FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackService.class) public interface PaymentService { @GetMapping(value = "/paymentSQL/{id}") CommonResult<Payment> paymentSQL(@PathVariable("id") Long id); }
🔶 Implement interface fallback
@Component public class PaymentFallbackService implements PaymentService { @Override public CommonResult<Payment> paymentSQL(Long id) { return new CommonResult<>(44444, "Service degradation return,---PaymentFallbackService", new Payment(id, "errorSerial")); } }
🔶 Business class addition method:
// ---------------------------OpenFeign----------- @Resource private PaymentService paymentService; @GetMapping("/consumer/openfeign/paymentSQL/{id}") public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){ return paymentService.paymentSQL(id); }
🔶 test
visit: http://localhost:84/consumer/openfeign/paymentSQL/1
{"code":200,"message":"from mysql, serverPort: 9003","data":{"id":1,"serial":"000001"}} Or, load balancing {"code":200,"message":"from mysql, serverPort: 9004","data":{"id":1,"serial":"000001"}}
Close 9003 and 9004
visit: http://localhost:84/consumer/openfeign/paymentSQL/1
{"code":44444,"message":"Service degradation return,---PaymentFallbackService","data":{"id":1,"serial":"errorSerial"}}
10, Rule persistence
Reason: once we restart the application, sentinel rules will disappear, and the production environment needs to persist the configuration rules
Solution: persist the flow restriction configuration rules into Nacos and save them. As long as a rest address of 8401 is refreshed, the flow control rules on sentinel console can be seen. As long as the configuration in Nacos is not deleted, the flow control rules on sentinel. On 8401 remain valid.
Steps:
🔶 POM dependency, add the configuration to microservice 8401 (which can be viewed in Gitee)
<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> </dependency>
🔶 YML configuration
server: port: 8401 spring: application: name: cloudalibaba-sentinel-service cloud: nacos: discovery: server-addr: localhost:8848 sentinel: transport: dashboard: localhost:8080 # Configure sentinel dashboard address port: 8719 # The default port is 8179. If it is occupied, it will automatically scan from 8719 to + 1 until an unoccupied port is found datasource: ds1: nacos: server-addr: localhost:8848 dataId: cloudalibaba-sentinel-service groupId: DEFAULT_GROUP data-type: json rule-type: flow management: endpoints: web: exposure: include: '*' feign: sentinel: enabled: true
🔶 nacos configuration
json inside
[ { "resource":"/testHotKey", "limitApp":"default", "grade":1, "count":1, "strategy":0, "controlBehavior":0, "clusterMode":false } ]
explain:
- Resource: resource name;
- limitApp: source application;
- grade: threshold type, 0 indicates the number of threads, 1 indicates QPS;
- count: single machine threshold;
- strategy: flow control mode, 0 indicates direct, 1 indicates association, and 2 indicates link;
- controlBehavior: flow control effect. 0 means fast failure, 1 means warm up, and 2 means queuing
- clusterMode: whether to cluster.
Start 8401 and visit multiple times to test: http://localhost:8401/testHotKey
It can be found in the flow control rules:
Restarting the microservice will not be affected.