Hello, I’m Xiao Dai. A man who wants to be a big talk about architecture! If you also want to be the person I want to be, or point a concern to be a companion, let small dish no longer lonely!
This article focuses on Sentinel in the SpringCloud
If necessary, you can refer to it
If helpful, do not forget thumb up pervious
WeChat public account has been opened, XiaoDai Liang remember, did not pay attention to the students remember to pay attention!
In the last article, we learned about one of the most important components of microservices — the service Gateway, the Gateway. We can’t deny the benefits that micro service brings to us when we take the essence and discharge the bran. Among them, the benefits of carrying high concurrency are so that major companies flock to it!
But if you want to accept high concurrency, you have to accept the problems that come with it. In the microservice architecture, we split the business into services, and one of the benefits of this is the burden sharing, where one service fails and the next service fails. But services can be invoked from one service to another, and services are not guaranteed to be 100% available, either because of the network or because of themselves, the few 9s that companies are looking for now! If there is a problem with a single service, there will be a network delay in calling this service. At this time, if there is a large number of network influx, it is bound to form a pile of tasks, leading to service failure!
Empty mouth, side dish to give you the whole example:
OrderController
Here we simulate the ordering scenario through the interface, where we simulate the network latency scenario through thread sleep. Next we need to change the number of concurrent threads in Tomcat
applicatio.yaml
The default number of concurrency for server: tomcat: max-threads: 10 # is 200
When all this is ready, we still need the help of the pressure measuring tool JMeter at this time (for those who can’t operate it, see the following for details).
- First, open the JMeter software and select New Thread Group
- Sets the number of request threads
- Set up the HTTP request sampler
- Sets the interface of the request
Complete the steps above and click on Start. Before testing, though, let’s make sure both APIs are accessible:
When a large number of requests are sent to the interface that creates the order, we access the Detail API through the web page and find that the request keeps blocking and will not connect until later!
This is definitely a development bomb, and this is the problem with high concurrency. Congratulations on witnessing a service avalanche of problems. That might as well with this interest to continue to look down, will give you a surprise.
Sentinel
A service avalanche
We started by directly seduce you with the service avalanche, I don’t know if you are tempted, if you don’t want your project online environment to face the same problem, quickly set up a project, casual action can often get you a promotion and pay rise!
In a distributed system, due to network reasons or its own reasons. A service is not always 100% available. If a service has a problem, the thread that calls the service will block. In this case, if a large number of requests come in, multiple threads will block and wait, causing the service to crash. Due to the dependency between services, the fault will be spread, and under the mutual influence, it will cause disastrous and serious consequences to the whole micro-service system, which is the “avalanche effect” of service failure!
At the very beginning, the three services of service A~C called each other happily, responded quickly and worked hard for their owners
The good times did not last long, the host was angry, and the quantity came up. Perhaps because service C is not robust enough, service C goes down one day, but service B still relies on service C and makes service calls all the time
At this time we may not be aware of the seriousness of the problem, just suspect that the request may be too much, resulting in the server card. The request continues to be sent. Service A is also not aware of the problem at this time, and wonders whether Service B has been lazy and hasn’t returned the response to it. Meanwhile, it continues to send the request. But by this time requests were piling up on Service B, and one day Service B was getting tired
At this point, people start to complain about service A, not realizing that the underlying service A still relies on service B and service C, and both service B and service C fail. Service A then realizes why Service B has not returned A response for so long, since Service B is also dependent on Service C. But by this time it was too late, and the requests kept coming in and piling up, all to a surprisingly similar end, leading to an outage. But there is one difference is that after the outage of service A needs to carry users of all kinds of abuse ~
Sad stories remind us that microservice architectures are not that reliable. Sometimes it’s just a matter of hanging, for a variety of reasons, such as inappropriate capacity design, slow response of a method under high concurrency, or a machine running out of resources. If we don’t take action, we’ll just sit back and continue to cycle through server restarts. But we may not be able to eliminate the source of the avalanche, but if we make a good preparation for fault tolerance after the occurrence of the problem, to ensure that the next service problems, will not affect the normal operation of other services, each service from the home to sweep the snow, do independent, snow falls without avalanche!
Second, fault tolerant scheme
Want to prevent the spread of avalanches, it is necessary to do a good job in the service of fault tolerance, fault tolerance is to protect themselves from other teammates pit, brought into the ranks of the head! So what are some of the fault-tolerant ideas we have?
1) Isolation scheme
It means that the system is divided into several service modules according to certain principles, and each module is independent of each other without strong dependence. When a fault occurs, it can isolate the problem and impact within a module without spreading the risk, involving other modules and affecting the overall system service. The common isolation methods are: thread isolation and semaphore isolation:
2) Timeout scheme
When the upstream service invokes the downstream service, a maximum response time is set. If the downstream service does not respond after this time, the connection is disconnected and the thread is released
3) Current limiting scheme
Current limiting is to limit the input and output flow of the system to achieve the purpose of protecting the system. In order to ensure the stable operation of the system, it is necessary to limit the flow and take a few measures to complete the purpose of limiting the flow once the threshold value is reached
There are many flow limiting strategies, and we will consider a special paper on how to limit flow
4) fuse scheme
In the Internet system, when the downstream service slows down or fails due to excessive access pressure, the upstream service can temporarily cut off the call to the downstream service in order to protect the overall availability of the system. This measure of sacrificing the part to preserve the whole is called a circuit breaker
Among them, the fuse can be divided into three states:
- Fuse Closed state
The state of the fuse in which the service does not fail, placing no restrictions on the invocation of the caller
- Fuse Open state
Subsequent calls to the service interface no longer travel over the network and directly execute the local fallback method
- Half-Open state
Attempting to restore the service invocation, allowing limited traffic to invoke the service, and monitoring the success rate. If the success rate reaches the expectation, it indicates that the service has been restored and entered the circuit-breaker shutdown state. If the success rate remains low, the circuit breaker is reentered
5) The downgrade plan
Downgrading is all about providing a Plan B for the service, and when the service does not work, it is a Plan B
There are many options, but it’s hard to say which one is the best. In the developer world, there is no best, only the best fit. If writing a fault tolerant solution is often more error-prone (except for those who are skilled), then to solve this problem, we might as well use a component that has been implemented for me by a third party!
Fault-tolerant components
1) Hystrix
Hystrix is an open source latency and fault tolerance library for Netflix that isolates access to remote systems, services, or third-party libraries, preventing cascading failures, and improving system availability and fault tolerance
2) Resilience4J
Resilience4J is a lightweight, simple, well-documented and well-equipped fuse breaker that is the preferred alternative to Hystrix. SpringBoot 1.x/2.x is supported, and monitoring is integrated with several major products such as Prometheus
3) Sentinel
Sentinel is an open-source implementation of Alibaba’s circuit breaker, which has also been widely adopted within Alibaba and can be said to be very stable
The difference
Fault-tolerant component has a lot of actually, but each have coquetude, explain the different place of these 3 kinds of components respectively below, how to choose, consider carefully!
function | Sentinel | Hystrix | resilience4j |
---|---|---|---|
Isolation strategy | Semaphore isolation (concurrent thread number limit) | Thread pool isolation/semaphore isolation | Semaphore isolation |
Circuit breaker downgrade strategy | Based on response time, outlier rate, outlier number | Based on the anomaly ratio | Based on the anomaly rate, response time |
Real-time statistical implementation | Time Sliding Window (LEAPArray) | Time Sliding Window (based on RXJava) | Ring Bit Buffer |
Dynamic rule configuration | Support for multiple data sources | Support for multiple data sources | Support co., LTD. |
scalability | Multiple extension points | The form of the plug-in | Form of interface |
Annotation-based support | support | support | support |
Current limiting | Based on QPS, it supports flow limiting based on calling relationships | Limited support | Rate LImiter |
Traffic shaping | Support preheat mode, uniform mode, preheat queuing mode | Does not support | Simple Rate Limiter mode |
System adaptive protection | support | Does not support | Does not support |
The console | Provides ready-to-use console, configurable rules, view second level monitoring, machine discovery, and more | Simple monitoring view | Do not provide console, can be connected to other monitoring systems |
It has been said before that a rookie who wants to be accepted and widely used must have good features to break out of the established circle. As a new microservice, Sentinel will only be accepted if it has desirable features. That’s why Sentinel is the main character in this article. Take a closer look at it!
4. Know Sentinel
Before we can learn to use a component, we need to know what the component is.
1) What is Sentinel
Sentinel (Traffic Defender for Distributed Systems) is a comprehensive service fault tolerant solution from Alibaba. It takes the flow as the entry point, and protects the stability of the service from multiple dimensions, such as flow control, fuse degradation, system load protection and so on.
2) features
- Rich application scenarios: Sentinel has undertaken the core scenarios of Alibaba’s traffic during the Double 11 promotion in nearly 10 years. Able to handle scenarios such as seckill, message peak clipping, cluster flow control, real-time fusing downstream unavailable applications, etc
- Complete real-time monitoring: Sentinel provides real-time monitoring capabilities. From the console, you can see data for individual machines connected to your application, or even aggregates for clusters of 500 or less
- Broad open source ecology: Sentinel provides modules that integrate with other open source frameworks out of the box and can be accessed quickly with simple configuration by introducing relevant dependencies
- Complete SPI extension points: Sentinel provides a simple to use, complete SPI extension interface. You can quickly customize the logic by extending the interface. For example, custom rule management, adapting to dynamic data sources, etc
3) Components
- Core Library (Java Client) : It does not depend on any framework/library, can run on all Java runtimes, and has good support for Dubbo and SpringCloud
- Dashboard: Developed based on SpringBoot, it can be packaged and run directly without the need for additional application containers such as Tomcat
Get started with Sentinel
Since Sentinel has two components, let’s discuss them separately
1) Core library usage
The most critical step is to introduce dependencies
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
Then write a test controller
@RestController @RequestMapping("order") public class OrderController { private final static Logger LOGGER = LoggerFactory.getLogger(OrderController.class); @getMapping ("/create/{id:.+}") public String createOrder(@PathVariable String ID) {logger.info (" To order [{}] ", id); Logger.info (" Order [{}] item successfully ", ID); return "success"; } @getMapping ("/{id:.+}") public String Detail (@pathVariable String id) {return stringUtils. join(" get ", "id "," id ", "id "); "Goods of "); }}
2) Use of console
With its sophisticated console, Sentinel has caught the heart of Chinese development. Many people saw the use of the console and chose it without hesitation!
- First we need to download the console JAR package to start running, download the address
- After downloading, enter the download directory and start with the following command, then access
localhost:8080
, you can see the page
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar Sentinel dashboard -, version 1.8.1. Jar
- Login console (Sentinel/Sentinel)
At this point we have successfully entered the Sentinel console page, is not easy to get started. But the console is still empty, and that’s because we haven’t configured the console yet. Let’s go back to the store-order order service and configure it in Application.yaml:
Sertinel.transport. Port is an optional port number used to communicate with the console. Sentinel. Transport. Dashboard for console access to the address
After the configuration is complete, we can start the store-order service and look at the console to see that the store-order service already exists
For those of you who are wondering, what is the port used to communicate with the console? There are problems, there is progress! Here we can take a look at how the console works
When the Sentinel application starts, we need to register our microserver on the console, which is to specify the address of the console in the configuration file, which is sure. However, the so-called port used to communicate with the console means that each of our services will pass data to the console through this port, and the console can also call the monitor in the micro-service through this port to obtain various information of the micro-service. This port is therefore essential, and each service needs to have a separate port number.
3) Basic concepts
- resources
A resource is what Sentinel wants to protect. A resource is the key concept behind Sentinel, which enables anything in a Java application, be it a service, a method, or even a piece of code.
- The rules
The so-called rules are used to define how to protect the resources. It acts on the resources and defines how to protect the resources, mainly including flow control rules, fuse downgrading rules and system protection rules
Let’s look at a simple example where we set QPS to 1 for the order/{id} API
As we keep refreshing the page, we’ll see that we’ve got flow control
In this case the order/{id} refers to the resource and the QPS threshold we set is the rule
4) Important functions
Before we can learn to use Sentinel, we need to know what Sentinel can do for us
(1)Flow control
Flow control is a commonly used concept in network transmission. It is used to adjust the data of network packets. Requests arriving at any time tend to be random and uncontrollable, and the system’s processing capacity is limited. The traffic needs to be controlled according to the processing capacity of the system. Sentinel acts as a dispatcher that can adjust random requests to the appropriate shape as needed.
(2)Fusing the drop
When the unstable performance of a resource in the call link is detected, for example, the request response time is long or the abnormal proportion is increased, the call of this resource is restricted to make the request fail quickly, so as to avoid affecting other resources and causing cascading failure
Sentinel solves this problem in two ways
- Limit by the number of concurrent threads
Sentinel reduces the impact of unstable resources on other resources by limiting the number of concurrent threads of a resource. When a resource becomes unstable, such as a longer response time, the immediate impact on the resource is a gradual build-up of threads. When the number of threads builds up to a certain number on a particular resource, a new request for that resource is rejected. The stack thread does not continue to accept requests until it has completed its task
- Resources are degraded by response time
In addition to controlling the number of concurrent threads, Sentinel can quickly degrade unstable resources through response time. When a dependent resource experiences a long response time, all access to that resource is denied outright and is not resumed until the specified time window has passed
Here’s the difference between a mouth and Hystrix
The principles of both are actually the same. When a resource has a problem, let it fail quickly, without affecting other resource services. But the implementation of the restriction is different
- Hystrix uses thread pool isolation, which has the advantage of isolation between resources, but the disadvantage is that it increases the cost of thread context switching
- Sentinel uses a resource constraint based on the number of concurrent threads and response time
Personally, I think Sentinel handles restrictions better
(3)System load protection
Sentinel also provides adaptive protection capability of system dimensions. When the system is under heavy load, continuing to let requests in May cause the system to crash and fail to respond. In a clustered environment, traffic that is supposed to be carried by this machine is forwarded to other machines. If other machines are on the brink of failure, Sentinel provides a protective mechanism to balance the incoming flow and load of the system so that the system can handle as many requests as it can handle.
5) Flow control rules
The flow control rules were briefly demonstrated above when we explained the basic concepts of Sentinel. Flow control is used to monitor indicators such as QPS (query rate per second) or concurrent threads of application traffic, and control the flow when it reaches a specified threshold, so as to avoid being overwhelmed by instantaneous peak traffic, so as to ensure high availability of the application.
Simple configuration
Cluster point link –> to select corresponding resources –> to add flow control
- Resource name: unique name, default is the request path, support customization
- For source: Specifies which microservice to limit the flow. Default is default (source indiscriminate, all limit)
-
Threshold type/single machine threshold:
- QPS (requests per second) : Limits the flow when the QPS calling this interface reaches a threshold
- Thread count: Limits the flow when the number of threads calling this interface reaches a threshold
- Clustering or not: Clustering is not demonstrated here for now
Advanced configuration
When we click on the Advanced option, we can see that there are two additional features
The flow control mode is divided into three kinds
- Direct (default) : turn on current limiting when the interface reaches a current limiting condition
- Association: When the associated resource reaches the flow limit condition, turn on the flow limit (suitable for application concession).
- Link: Enables current limiting when a resource from an interface reaches a current limiting condition
1. Associated flow control
We have already demonstrated direct flow control above, so let’s talk about how to use the associative flow control directly here
It is also very simple to use, as long as you add the associated resources. As long as the QPS of the associated resource /order/create/{id} exceeds 1 per second. Then /order/{id} triggers flow control. This is your impulse, I’ll pay
After setting, we need to ask our old helper JMeter to help test:
The QPS of /order/create/{id} is already well over 1, and we try again to access /order/{id} and find that the flow is restricted!
2. Link flow control
Link flow control mode refers to turning on flow limiting when a resource from an interface reaches a flow limiting condition. Its functionality is somewhat similar to source-specific configuration items, except that source-specific is for parent microservices, while link-flow control is for parent interfaces, which means it is more granular
This mode is a bit troublesome to use, so we need to transform the code:
OrderService
OrderController
application.yaml
Then customize the Sentinel context filtering class FilterContextConfig:
Next we add the configuration to the Sentinel console flow control:
If /order/_datail02 is used as the entry point, it will be flow controlled, but /order/_datail01 will not
So we know that the link mode entry resources are specific to the method interface
6) Degradation rules
Deduction rules refer to the demoting of a service when certain conditions are met. Sentinel offers three metrics:
-
Slow call ratio
When the mean corresponding time of a resource exceeds the threshold (in ms), the resource enters a quasi-degraded state. If five requests continue to come in for the next 1s, and their RT continues to exceed this threshold, the method is degraded for the next time window (in units of s).
- Abnormal proportion
When the resource exception ratio per second exceeds the threshold, the resource goes into a reduced state, where calls to this method are automatically returned for the next time window (s). Abnormal ratios are assigned in the range [0.0, 1.0]
- Number of abnormal
When the number of exceptions in the last 1 minute of the resource exceeds the threshold, it is directly degraded. However, it should be noted here that since the statistical time window is at the level of minutes, if the time window is less than 60s, the fuse state may still be re-entered after the end of the fuse state
7) Hot Rules
The hot spot parameter flow control rule is a more fine-grained flow control rule that allows rules to be specific to parameters. And here we can look at it in our code and see how it works. Okay
@SentinelResource("order") @SentinelResource("order") @SentinelResource("order") @SentinelResource("order") @SentinelResource("order") String arg2) { return StringUtils.join(arg1, arg2); }
The API receives two parameters, arg1 and arg2, at which point we add parameter flow control to the resource
Once the above configuration is complete, we can test it in the browser
When the second parameter is set, flow control will not be triggered regardless of the number of flushes per second
When the parameter is the first, flow control is triggered whenever QPS exceeds 1
This configuration also has advanced options to limit the parameters more granular, which will not be demonstrated here.
8) System rules
The system protection rule is to control the entry flow at the application level and monitor the application data from the five dimensions of the overall Load, RT, thread number, entry QPS and CPU utilization of a single machine, so that the system can run as fast as possible in the maximum throughput while ensuring the overall stability of the system
- Load:Only valid for Linux/ UNIX. System protection is triggered when the load of the system exceeds the threshold and the current number of concurrent threads on the system exceeds the system capacity. System capacity is defined by the system
maxQPS * minRT
Calculate and go out, the reference value that sets can refer toCPU cores * 2.5 - RT: System protection is triggered when the average RT of all inlet flows on a single machine reaches a threshold, in milliseconds
- Thread count: Protection is triggered when the number of concurrent threads for all incoming traffic on a single machine reaches a threshold
- Inlet QPS: System protection is triggered when the QPS of all inlet flows on a single machine reaches the threshold
- CPU utilization: System protection is triggered when the CPU utilization of all incoming traffic on a single machine reaches a threshold
9) Authorization rules
In some scenarios where we need to determine whether a request is allowed based on the source of the call, we can use Sentinel’s source access control capabilities. Source access control determines whether a resource can pass based on the source of the request for the resource.
- Whitelist: Only the request source is on the whitelist
- Blacklist: request source located in the blacklist is not approved, the rest are released through
So the question is, what is a flow control app? To use this flow control application, we also need to handle the source with the RequestOriginParser interface in Sentinel. Whenever a Sentinel-protected interface resource is accessed, Sentinel calls the RequestOriginParser implementation class to resolve the access source
CustomRequestOriginParser
public class CustomRequestOriginParser implements RequestOriginParser { @Override public String parseOrigin(HttpServletRequest httpServletRequest) { return httpServletRequest.getParameter("api"); }}
Then we add authorization rules
This rule will only succeed if the request URL contains the parameter API =detail03, otherwise it will fail. Here are the results
Extend Sentinel
1) @ SentinelResource
This note we have used above, I do not know whether the friends have noticed, above to avoid not to speak is to introduce in this detail!
The purpose of this annotation is to define resource points. Once a resource point has been defined, the Sentinel console can be used to set the flow limiting and degradation policies to protect the resource point. The annotation can also be used to specify the handling policy when an exception occurs.
When we click on the annotation, we can see that there are many attributes in the annotation
attribute | role |
---|---|
value | Resource Point Name |
blockHandle | The name of the function that handles BlockException. The function requires: 1. Must be public 2. Return type parameters should be the same as the original method 3. Default needs to be in the same class as the original method. If you want to use functions from other classes, you can configure the BlockHandlerClass and specify the methods in the BlockHandlerClass |
blackHandlerClass | The class that holds BlockHandler must use the corresponding handler functionstatic modified |
fallback | Used to provide fallback processing logic when an exception is thrown. The fallback function can handle all types of exceptions (except those excluded in ExceptionStoIgnore). The function requires: 1. Return the same type as the original method 2. The parameter type should match the original method 3. Default needs to be in the same class as the original method. If you want to use a function from another class, you can configure the FallbackClass and specify the corresponding method |
fallbackClass | The class that holds Fallback must be used by the corresponding handlerstatic modified |
defaultFallback | Used for generic fallback logic. The default fallback function can handle all types of exceptions. If both FALLBACK and DefaultFALLBACK are configured, then FALLBACK shall prevail. <br/>1. <br/>2. <br/>2. The method argument list is empty or has an argument of type Throwable. <br/> > <br/> > <br/> > If you want to use functions from other classes, you can configure the FallbackClass and specify methods within the FallbackClass. |
exceptionsToIgnore | Specifies which exceptions to exclude. Excluded exceptions are not counted in the exception statistics, nor are they entered into Fallback logic, but are thrown as is. |
exceptionsToTrace | Exception that needs to be traced |
We’re going to do a quick demo here
- Define flow limiting and degradation methods in the same class as the original method
- Flow limiting and degradation method definitions are not in the same class as the original method
Then let’s do a simple flow control setup:
Results:
This is definitely more friendly!
2) Sentinel rule persistence
Those of you who have already tried this out may have noticed a problem that when our project is restarted, or the Sentinel console is restarted, the configuration is cleared! This is because these rules are stored in memory by default, which is a big problem! So rule persistence is a must! Of course, Sentinel already has good support for this function. The processing logic is as follows:
To be honest, configuration class code is a little long, here directly posted code, there is a need for partners can be copied in the past direct use!
public class FilePersistence implements InitFunc { @Override public void init() throws Exception { String ruleDir = new File("").getCanonicalPath() + "/sentinel-rules"; String flowRulePath = ruleDir + "/flow-rule.json"; String degradeRulePath = ruleDir + "/degrade-rule.json"; String systemRulePath = ruleDir + "/system-rule.json"; String authorityRulePath = ruleDir + "/authority-rule.json"; String paramFlowRulePath = ruleDir + "/param-flow-rule.json"; this.mkdirIfNotExits(ruleDir); this.createFileIfNotExits(flowRulePath); this.createFileIfNotExits(degradeRulePath); this.createFileIfNotExits(systemRulePath); this.createFileIfNotExits(authorityRulePath); this.createFileIfNotExits(paramFlowRulePath); / / flow control rules sentinel ReadableDataSource < String, List < FlowRule > > flowRuleRDS = new FileRefreshableDataSource < > (flowRulePath, flowRuleListParser ); FlowRuleManager.register2Property(flowRuleRDS.getProperty()); WritableDataSource<List<FlowRule>> flowRuleWDS = new FileWritableDataSource<>( flowRulePath, this::encodeJson ); WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS); ReadableDataSource<String, List<DegradeRule>> degradeRuleRDS = new FileRefreshableDataSource<>( degradeRulePath, degradeRuleListParser ); DegradeRuleManager.register2Property(degradeRuleRDS.getProperty()); WritableDataSource<List<DegradeRule>> degradeRuleWDS = new FileWritableDataSource<>( degradeRulePath, this::encodeJson ); WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS); / / system rules ReadableDataSource < String, List < SystemRule > > systemRuleRDS = new FileRefreshableDataSource < > (systemRulePath, systemRuleListParser ); SystemRuleManager.register2Property(systemRuleRDS.getProperty()); WritableDataSource<List<SystemRule>> systemRuleWDS = new FileWritableDataSource<>( systemRulePath, this::encodeJson ); WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS); ReadableDataSource<String, List<AuthorityRule>> authorityRuleRDS = new FileRefreshableDataSource<>( authorityRulePath, authorityRuleListParser ); AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty()); WritableDataSource<List<AuthorityRule>> authorityRuleWDS = new FileWritableDataSource<>( authorityRulePath, this::encodeJson ); WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS); // ReadableDataSource<String, List<ParamFlowRule>> paramFlowRuleRDS = new FileRefreshableDataSource<>( paramFlowRulePath, paramFlowRuleListParser ); ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty()); WritableDataSource<List<ParamFlowRule>> paramFlowRuleWDS = new FileWritableDataSource<>( paramFlowRulePath, this::encodeJson ); ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS); } private final Converter<String, List<FlowRule>> flowRuleListParser = source -> JSON.parseObject( source, new TypeReference<List<FlowRule>>() { } ); private final Converter<String, List<DegradeRule>> degradeRuleListParser = source -> JSON.parseObject( source, new TypeReference<List<DegradeRule>>() { } ); private final Converter<String, List<SystemRule>> systemRuleListParser = source -> JSON.parseObject( source, new TypeReference<List<SystemRule>>() { } ); private final Converter<String, List<AuthorityRule>> authorityRuleListParser = source -> JSON.parseObject( source, new TypeReference<List<AuthorityRule>>() { } ); private final Converter<String, List<ParamFlowRule>> paramFlowRuleListParser = source -> JSON.parseObject( source, new TypeReference<List<ParamFlowRule>>() { } ); private void mkdirIfNotExits(String filePath) throws IOException { File file = new File(filePath); if (! file.exists()) { file.mkdirs(); } } private void createFileIfNotExits(String filePath) throws IOException { File file = new File(filePath); if (! file.exists()) { file.createNewFile(); } } private <T> String encodeJson(T t) { return JSON.toJSONString(t); }}
Then under the resources to create the configuration directory meta-inf/services, then add files com. Alibaba. CSP. The sentinel. Init. InitFunc configuration is added in the file type the full path
This will generate the Sentinel configuration file when we launch the project
When we add a flow control rule to the console, the corresponding JSON file will have the corresponding configuration
This completes Sentinel’s persistence capabilities, and we have finished our introduction to Sentinel in the SpringCloud!
Stay tuned for more articles on SpringCloud components in the future!
Don’t talk, don’t be lazy, and dishes together to do a blowing cattle X architecture program ape bar ~ point a concern to do a companion, let dishes no longer lonely. See you later!
Today you work harder, tomorrow you will be able to say less words for people!
I am small dish, a strong man with you. 💋
WeChat public account has been opened, XiaoDai Liang remember, did not pay attention to the students remember to pay attention!