Hello everyone, I am a side dish.
A man who hopes to be about architecture ! If you also want to be the person I want to be, otherwise click on your attention and be a companion, so that Xiaocai is no longer alone!
This article mainly introduces Sentinel in
If necessary, you can refer to
If it helps, don’t forget 160d911123c10d ❥
The WeChat public account has been opened, , students who are not following please remember to pay attention!
In the previous article, we have learned that one of the important components in --- 160d911123c18a service gateway Gateway . While we take the essence and drain the chaff, there is no denying the benefits of microservices. Among them, the advantage of carrying high concurrency is that major companies are rushing!
But if you want to receive high concurrency, you must naturally receive a series of problems it brings. In the microservice architecture, we split the business into individual services. One of the benefits of this is to share the pressure. If one service cannot withstand it, the next service will be on top. However, services and services can be called mutually. Due to network reasons or their own reasons, services cannot be guaranteed to be 100% available, that is, several 9 (99.99%, 99.999%) that major companies are now looking for are available! If there is a problem with a single service, there will be a network delay when calling this service. If there is a large influx of network at this time, it will inevitably form a stack of tasks and cause the service to be paralyzed!
There is no proof for nothing, and the side dish will give you the whole example:
OrderController
Here we simulate the scenario of placing an order through the interface, and the scenario of network delay is simulated by the way of thread sleep. Next we also need to change the number of concurrent threads in tomcat
applicatio.yaml
server:
tomcat:
max-threads: 10 # 默认的并发数为200
When all this is ready, we also need at this time (for those who can’t operate, see the following for details)
- First open the Jmeter software, select the new thread group
- Set the number of request threads
- Set up HTTP request sampler
- Set the requested interface
After completing the above steps, you can click Start. But before testing, we make sure that both APIs are accessible:
Then start the stress test. When a large number of requests are sent to the order creation interface, we visit detail
API through the web page and find that the requests have been blocked, and it will be connected after a while!
This is undoubtedly a development bomb, and this is the problem caused by high concurrency. Seeing this, congratulations on successfully witnessing a service avalanche. You might as well continue to look down with this interest, it will surprise you.
Sentinel
1. Service avalanche
At the beginning, we directly used the service avalanche to seduce you. I don’t know if your heart is moved. If you don’t want your project to face the same problem in the online environment, hurry up for the project. Inadvertent actions can often make you get a promotion and a salary increase!
In a distributed system, due to network reasons or own reasons. Services are generally not guaranteed to be 100% available. If a service has a problem, the thread will be blocked when calling this service. If a large number of requests flow in at this time, multiple threads will block and wait, which will cause the service to be paralyzed. However, due to the dependence between services and services, failures will propagate. Under mutual influence, it will cause catastrophic and serious consequences for the entire system. This is the 160d911124e323 "avalanche effect" service failures!
At the beginning, the A~C called each other happily, and the response was very fast, and they worked very hard for the master.
The good times didn't last long, the master was on fire, and the amount of concurrency increased. Maybe because service C is not robust enough, service C is down one day, but service B still relies on service C, making service calls continuously
At this time, everyone may not realize the seriousness of the problem, but suspect that there may be too many requests, causing the server to become stuck. The request continues to be sent, and service A is not aware of the problem at this time. While wondering if service B is lazy, why doesn't it return the response to it, it continues to send the request. But at this time, requests are all piled up on service B, and finally one day service B is also tired and has problems.
At this time, people began to complain about service A, but they didn't know that the bottom layer of service A still relied on service B and service C, and then both service B and service C were down. Only then did Service A figure out why Service B did not return a response for so long before, and it turns out that Service B also depends on Service C! But it was too late at this time. Requests were continuously received and piled up, and the results were surprisingly similar, and they were also the result of downtime. But one difference is that after service A goes down, it needs to carry all kinds of curses from users~
The sad story warns us that the microservice architecture is not so reliable. Sometimes it really means hanging up. There are various reasons, unreasonable capacity design, slow response of a certain method under high concurrency, or a certain machine's resource exhaustion. If we don't take measures, we can only wait to die, and continue to cycle in restarting the server. But we may not be able to eliminate the source of the avalanche, but if we are prepared for fault tolerance after the problem occurs, to ensure that the next service has a problem, it will not affect the normal operation of other services, and each service will be independent and independent. Snow falls without avalanches !
Second, the fault-tolerant solution
If you want to prevent the spread of avalanches, you must be fault-tolerant in your service. To put it bluntly, fault-tolerance is to protect yourself from being pitted by other teammates and being brought into the ranks of giving heads! So what are our fault-tolerant ideas?
1) Isolation plan
It refers to dividing the system into several service modules according to certain principles, and each module is independent of each other without strong dependence. When a fault occurs, the problem and impact can be isolated within a certain module without spreading the risk, without involving other modules, and without affecting the overall system service. Common isolation methods are: thread isolation and semaphore isolation:
2) Timeout scheme
When the upstream service calls the downstream service, set a maximum response time. If the downstream service does not respond after this time, then 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, once the threshold that needs to be restricted is reached, it is necessary to limit the flow and take a few measures to accomplish the purpose of restricting the flow
There are many current limiting strategies, and an article on how to limit current will be considered later.
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 and preserving the whole is called fusing
There are three states of fusing:
- Fuse closed state (Closed)
When the service is not faulty, the state of the fuse does not impose any restrictions on the caller's call
- Fuse open state (Open)
Subsequent calls to this service interface no longer go through the network, and directly execute the local fallback method
- Half-open state (Half-Open)
Try to restore the service call, allow limited traffic to call the service, and monitor the success rate. If the success rate reaches the expected, it means that the service has been restored and enters the fuse-off state; if the success rate is still low, it re-enters the fuse-off state
5) Downgrade plan
Downgrading is actually to provide a B plan for the service. Once the service fails, B plan
There are actually many options, but it is difficult to say which one is the best. In the world of developers, there is no best, only the most suitable. If you write a fault-tolerant solution by yourself, it is often more error-prone (except those with advanced skills), then in order to solve this problem, we might as well use a third-party component that has been implemented for me!
Three, fault-tolerant components
1)Hystrix
Hystrix is a latency and fault-tolerant library open sourced by Netflix. It is used to isolate access to remote systems, services or third-party libraries to prevent cascading failures, thereby improving the availability and fault tolerance of the system
2)Resilience4J
Resilience4J is a very lightweight, simple, and very clear document, rich fuse tool, this is Hystrix officially recommended replacement. It supports SpringBoot 1.x/2.x version, and monitoring also supports integration with a variety of mainstream products such as prometheus
3)Sentinel
Sentinel is an implementation of Alibaba's open source circuit breaker, which has also been adopted on a large scale within Alibaba. It can be said to be very stable
the difference
There are actually many fault-tolerant components, but each has its own charm. The following explains the differences between these three components, how to choose, and carefully consider!
Features | Sentinel | Hystrix | resilience4j |
---|---|---|---|
Isolation strategy | Semaphore isolation (limiting the number of concurrent threads) | Thread pool isolation/semaphore isolation | Semaphore isolation |
Fuse downgrade strategy | Based on response time, abnormal ratio, abnormal number | Based on abnormal ratio | Based on abnormal ratio, response time |
Real-time statistics realization | Time sliding window (LeapArray) | Time sliding window (based on Rxjava) | Ring Bit Buffer |
Dynamic rule configuration | Support multiple data sources | Support multiple data sources | Limited support |
Scalability | Multiple extension points | The form of the plug-in | The form of the interface |
Annotation-based support | stand by | stand by | stand by |
Limiting | Based on QPS, support current limit based on call relationship | Limited support | Rate LImiter |
Traffic shaping | Support preheating mode, homogenizer mode, preheating queue mode | not support | Simple Rate Limiter mode |
System adaptive protection | stand by | not support | not support |
Console | Provide a ready-to-use console, configure rules, view second-level monitoring, machine discovery, etc. | Simple monitoring and viewing | No console provided, but can be connected to other monitoring systems |
As mentioned before, a rookie wants to be accepted and widely used by everyone, and it must have good characteristics to break out of the encirclement of the old brand. Then Sentinel as a rookie in microservices, can only be accepted by everyone if it has satisfactory functions. Therefore, the protagonist of this article is Sentinel , you might as well learn more!
Fourth, know Sentinel
Before learning to use a component, we first need to know what this component is.
1) What is Sentinel
Sentinel (distributed system traffic guard) is a comprehensive solution service fault tolerance open sourced by Ali. It takes the flow as the entry point, and protects the stability of the service from multiple dimensions such as flow control , fuse downgrade , system load protection
2) Features
- Rich application scenarios : Sentinel has undertaken the core scenarios of Alibaba's double eleven promotion in the past 10 years. Easier in scenarios such as spikes, message peak-cutting and valley-filling, cluster flow control, and real-time fuse of unavailable downstream applications
- complete real-time monitoring: Sentinel provides real-time monitoring functions. Through the console, you can see the data of a single machine connected to the application, and even the summary of clusters of less than 500 units
- Extensive open source ecology: Sentinel provides out-of-the-box integration modules with other open source frameworks. You only need to introduce related dependencies and perform simple configurations for quick access
- complete SPI extension point: Sentinel provides a simple, easy-to-use and complete SPI extension interface. The logic can be quickly customized by extending the interface. For example, custom rule management, adaptation of dynamic data sources, etc.
3) Components
- core library (Java client) : does not rely on any framework/library, can run in all Java runtime environments, and has good support for Dubbo and SpringCloud
- console (Dashboard) : Based on SpringBoot development, it can be run directly after packaging, without additional application containers such as Tomcat
Five, get started with Sentinel
Since Sentinel has two components, we will separately introduce
1) Use of core library
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("准备下单ID为 [{}] 的商品", id);
LOGGER.info("成功下单了ID为 [{}] 的商品", id);
return "success";
}
@GetMapping("/{id:.+}")
public String detail(@PathVariable String id) {
return StringUtils.join("获取到了ID为", id, "的商品");
}
}
2) Console use
Sentinel complete console, which actually captures the fate of the development of Chinese people. Many people saw the use of the console and chose it without hesitation!
- First, we need to download the Jar package of the console to start the operation, download address
- After downloading, enter the download directory and start by the following command, and then visit
localhost:8080
, you can see the page
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.1.jar
- Log in to the console (sentinel/sentinel)
At this point, we have successfully entered Sentinel . Is it very easy to get started? But the console here is still empty, that's because our project has not yet configured the console. Let's go back to the store-order order service and configure application.yaml
sertinel.transport.port
is an arbitrary port number, the port used to communicate with the console; sentinel.transport.dashboard
is the access address of the console
After the configuration is complete, we can start the store-order service. At this time, looking at the console, we can find that there is already a store-order service.
Some friends may find it strange, what is the port used to communicate with the console mentioned above? If there is a problem, there will be progress! Here we can take a look at the usage principle of the console by the way
When the Sentinel application starts, we need to register our microservice program to the console, that is, specify the address of the console in the configuration file. This is affirmative. But 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 use this port to call the monitoring program in the microservice to obtain various information about the microservice. therefore this port is essential, and each service needs to have a separate port number .
3) Basic concepts
- Resources
The so-called resource is what Sentinel wants to protect. Resource is the key concept of Sentinel, it can make any content in a Java application, it can be a service, it can be a method, or even a piece of code.
- rules
The so-called rules are used to define how to protect resources. They act on resources and define how to protect resources. They mainly include flow control rules, fuse degradation rules, and system protection rules.
Let's look at a simple example, we set the QPS of the API order/{id}
When we keep refreshing the page, we will find that the flow control has been carried out
Here order/{id}
refers to resource , the QPS threshold we set is rule
4) Important functions
Before we 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, which is used to adjust the data of network packets. Requests arriving at any time are often random and uncontrollable, and the processing capacity of the system is limited. We need to control the flow according to the processing capacity of the system. Sentinel, as an orchestrator, can adjust random requests to a suitable shape as needed.
(2) fuse downgrade
When an unstable performance of a resource in the call link is detected, such as a long request response time or an increase in the abnormal ratio, the call of this resource is restricted to make the request fail quickly to avoid affecting other resources. Cascading failure
Sentinel uses two methods to solve
- by the number of concurrent threads
Sentinel reduces the impact of unstable resources on other resources by limiting the number of concurrent threads for resources. When a certain resource is unstable, for example, the response time becomes longer, the direct impact on the resource is the gradual accumulation of the number of threads. When the number of threads accumulates to a certain amount on a specific resource, new requests for that resource will be rejected. The piled up threads will not start accepting requests until they complete their tasks
- resources through response time
In addition to controlling the number of concurrent threads, Sentinel can also quickly degrade unstable resources through response time. When the response time of the dependent resource is too long, all access to the resource will be directly denied, and will not resume until the specified time window has passed
Here is the difference between Hystrix and Hystrix
The principles of both are actually the same. When there is a problem with a resource, let it fail quickly without affecting other resource services. But the implementation of the restriction is different
- Hystrix uses a thread pool isolation method. The advantage is that it can isolate resources. The disadvantage is that it increases the cost of thread context switching.
- Sentinel uses the number of concurrent threads and response time to limit resources
I personally think that Sentinel handles restrictions better
(3) system load protection
Sentinel also provides system-dimensional adaptive protection capabilities. When the system load is high, if you continue to allow requests to enter, it may cause the system to crash and fail to respond. In a cluster environment, the traffic that should have been carried by this machine is forwarded to other machines. If other machines are on the verge of collapse at this time, Sentinel provides a corresponding protection mechanism to balance the ingress traffic and load of the system to ensure that the system handles the most requests within its capacity.
5) Flow control rules
The flow control rules were briefly demonstrated when we explained the basic concepts of Sentinel above. Flow control is used to monitor the QPS (query rate per second) or the number of concurrent threads and other indicators of application traffic. When the specified threshold is reached, the traffic is controlled to avoid being overwhelmed by instantaneous traffic peaks, thereby ensuring the high availability of the application.
simple configuration
cluster point link ---> select the corresponding resource ---> add flow control
- resource name : unique name, the default is the request path, support customization
- Targeting the source: specifies which microservice to limit the flow of, the default is default (the source is not distinguished, all restrictions)
threshold type/single machine threshold :
- QPS (requests per second) : current limit is performed when the QPS calling the interface reaches the threshold
- thread number : when the number of threads calling the interface reaches the threshold, the current limit will be performed
- is cluster: cluster is not demonstrated here temporarily
advanced configuration
We click on the advanced option to see that there are two additional functions
Among them, flow control mode is divided into three types
- Direct (default) : When the interface reaches the current limit condition, turn on the current limit
- associated : When the associated resource reaches the current limit condition, the current limit is turned on (suitable for application concessions)
- link: When the resource coming from an interface reaches the current limit condition, open the current limit
1. Associated flow control
direct flow control has been demonstrated above. Here we directly talk about how to use the associated flow control
The usage is also very simple, just add the associated resources. As long as /order/create/{id}
exceeds 1 per second. Then /order/{id}
will trigger flow control. This is you impulse, I pay
After setting, we need to ask our old helper help test it:
At this time /order/create/{id}
has far exceeded 1, and then we tried to access /order/{id}
, and found that the current limit has been reached!
2. Link flow control
The link flow control mode refers to: when the resource from a certain interface reaches the current limit condition, the current limit is turned on. Its function is a bit similar to the configuration item for the source, the difference is: for the source and is for the upper-level microservice, and the link flow control is for the upper-level interface, which means that its granularity is more fine
This mode is more troublesome to use, we need to modify the code:
OrderService
OrderController
application.yaml
Then customize the Sentinel context filter class FilterContextConfig
:
Next, we add configuration to the Sentinel
Then we looked at the test results and found that if /order/_datail02
is used as the entrance visit, flow control will be performed, while the /order/_datail01
visit will not be flow controlled.
Therefore, we know that link mode is for the method interface
6) Downgrade rules
The downgrade rule refers to the downgrade of the service when certain conditions are met. Sentinel provides three measurement conditions:
Slow call ratio
When the average response time of the resource exceeds the threshold (in ms), the resource enters a quasi-degraded state. If the next
1s
continues to enter5
requests, and their RT continues to exceed this threshold, then within the next time window (unit s), this method will be downgraded.
- Abnormal proportion
When the abnormal total per second of the resource / the ratio of the throughput exceeds the threshold, the resource will enter a reduced state, that is, within the next time window (unit s), calls to this method will automatically return. The value range of the abnormal ratio is
[0.0, 1.0]
- Number of exceptions
When the number of abnormal resources in the past 1 minute exceeds the threshold, it will be directly degraded. However, it should be noted here that since the statistical time window is at the minute level, if the time window is less than 60s, it may still enter the fusing state after the fusing state is ended.
7) Hot spot rules
The hot parameter flow control rule is a more fine-grained flow control rule, which allows the rule to be specific to the parameter. Here we can see how to use it in the code
@SentinelResource("order") // 不添加该注解标识, 热点规则不生效
@GetMapping("/_datail03")
public String detail03(String arg1, String arg2) {
return StringUtils.join(arg1, arg2);
}
The API receives two parameters arg1
and arg2
. At this time, we add parameter flow control to this resource
After finishing the above configuration, we can test in the browser
When the parameter is the second, the flow control will not be triggered no matter how many times it is refreshed per second
When the parameter is the first one, as long as the QPS exceeds 1, the flow control will be triggered
This configuration also has advanced options, which can limit the parameters in a more fine-grained manner, so I will not demonstrate it here.
8) System rules
The system protection rules are controlled from the application-level entrance traffic, from the overall Load, RT, thread count, entrance QPS, and CPU usage single machine to monitor application data, so that the system can run at the maximum throughput as much as possible. While ensuring the overall stability of the system
- Load: only valid for Linux/Unix. When the load of the system exceeds the threshold, and the current number of concurrent threads of the system exceeds the system capacity, the system protection will be triggered. The system capacity is
maxQPS * minRT
, and the reference value can be set as CPU cores* 2.5 - RT: When the average RT of all ingress traffic on a single machine reaches the threshold, system protection will be triggered, in milliseconds
- thread number: When the number of concurrent threads for all ingress traffic on a single machine reaches the threshold, the protection will be triggered
- Ingress QPS: When the QPS of all ingress traffic on a single machine reaches the threshold, the system protection will be triggered
- CPU usage rate: When the CPU usage rate of all ingress traffic on a single machine reaches the threshold, the system protection will be triggered
9) Authorization rules
In some scenarios, we need to determine whether the request is allowed to be released based on the source of the call. At this time, we can use the source access control function of Sentinel. source access control judges whether the resource can pass according to the request source of the resource.
- whitelist: can only pass if the request source is in the whitelist
- blacklist: requests that the source is in the blacklist will not be passed, and the rest will be passed
So the question is, flow control application? To use this flow control application, we also need to use RequestOriginParser interface in Sentinel to process the source. As long as the interface resources protected by Sentinel Sentinel will call RequestOriginParser 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
The function of this rule is that only when the request URL contains the parameter api=detail03
can the access succeed, otherwise it will fail. The following is the test result
Six, expand Sentinel
1)@SentinelResource
We have used this annotation above. I don’t know if the friends have noticed it. The reason for avoiding the above is for this detailed introduction!
The function of the annotation is to define the resource point. After we define the resource point, we can use the Sentinel console to set the current limit and downgrade strategy to protect the resource point. At the same time, the annotation can be used to specify the processing strategy when an exception occurs.
We can click into the annotation to see that there are many attributes in the annotation
Attributes | effect |
---|---|
value | Resource point name |
blockHandle | The name of the function that handles the BlockException. The function requirements are: 1. Must be public 2. The return type parameter must be consistent with the original method 3. By default, it must be in the same class as the original method. If you want to use functions of other classes, you can configure blockHandlerClass and formulate methods in blockHandlerClass |
blackHandlerClass | The class storing blockHandler, the corresponding processing function must be modified static |
fallback | Used to provide fallback processing logic when an exception is thrown. The fallback function can target all types of exceptions (except exceptions excluded in exceptionsToIgnore), the function requirements: 1. The return type is consistent with the original method 2. The parameter type needs to match the original method 3. The default needs to be the same as the original method Class. If you want to use functions of other classes, you can configure fallbackClass and specify the corresponding method |
fallbackClass | The class storing fallback, the corresponding processing function must be modified static |
defaultFallback | Used for general fallback logic. The default fallback function can handle all types of exceptions. If both fallback and defaultFallback are configured, the fallback shall prevail. Function requirements:<br/>1. The return type is consistent with the original method<br/>2. The method parameter list is empty, or there is a Throwable type parameter. <br/>3. The default method needs to be in the same class as the original method. If you want to use functions of other classes, you can configure fallbackClass and specify the methods in fallbackClass. |
exceptionsToIgnore | Specify which exceptions to exclude. The excluded exception will not be counted in the exception statistics, nor will it enter the fallback logic, but thrown out as it is. |
exceptionsToTrace | Exceptions that need to be traced |
Let's use it briefly here to demonstrate
- the current limiting and downgrading methods in the same class as the original method
- current limiting and downgrading method definitions are not in the same class as the original method
Then we make a simple flow control setting:
Visit results:
This way of prompting is obviously more friendly!
2) Sentinel rule persistence
Students who have already tried it may find a problem. When our project restarts or the Sentinel console restarts, the configuration will be cleared! This is because these rules are stored in memory by default, which is a big problem! Therefore rule persistence is an essential job! Of course, the Sentinel also supports this function well, and the processing logic is as follows:
To be honest, the configuration code is a bit long, and the code is posted directly here, and friends in need can copy it and use it directly!
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);
// 流控规则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);
// 系统规则
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 create the configuration directory resources
META-INF/services
, and then add the file com.alibaba.csp.sentinel.init.InitFunc
to add the full path of the configuration class in the file
In this way, when we start the project, the Sentinel configuration file will be generated
When we add a flow control rule in the console, the corresponding json file will have the corresponding configuration
At this point we have completed the persistence function of Sentinel, and here we have also completed the introduction of Sentinel in SpringCloud!
I will continue to organize articles about SpringCloud components later, so stay tuned!
Don't talk empty talk, don't be greedy, and be a X as an architecture with Xiaocai~ Follow me to be a companion, so Xiaocai is no longer alone. See you below!
If you work harder today, you will be able to say less begging words tomorrow!
I am Xiaocai, a man who becomes stronger with you.
💋
The WeChat public account has been opened, , students who have not followed please remember to pay attention!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。