Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Usage Analysis of Sentinel

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about the analysis of the use of Sentinel, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article. Let's take a look at it with the editor.

What can Sentinel be used for?

Current limit

Fuse degradation

Flow shaping

System load protection

For a detailed introduction to the concept of hot spot protection, please read https://github.com/alibaba/Sentinel/wiki/%E4%B8%BB%E9%A1%B5

Sentinel basic concept Resources

Resources are the key concepts of Sentinel. It can be anything in a Java application, for example, a service provided by an application, or a service provided by another application invoked by the application, or even a piece of code. In the next document, we will use resources to describe the code block. As long as the code defined by Sentinel API is the resource, it can be protected by Sentinel. In most cases, you can use method signatures, URL, or even service names as resource names to identify resources.

Rules

Rules set around the real-time status of resources can include flow control rules, circuit breaker degradation rules, and system protection rules. All rules can be adjusted dynamically in real time.

Using Sentinel to introduce Sentinel dependency com.alibaba.csp sentinel-core 1.8.0 to define resources and set rules

The following code defines a Java method to protect resources, and the rule is set to access once per second. You can find that the Sentinel takes effect through the console output.

Public class demo {public static void main (String [] args) {/ / configure rules. InitFlowRules (); while (true) {/ / 1.5.0 version can directly take advantage of the try-with-resources feature, automatic exit entry try (Entry entry = SphU.entry ("sentinel-test1")) {/ / protected business logic System.out.println ("business resource access successful!") ;} catch (BlockException ex) {/ / handle logical System.out.println controlled by flow ("Resource access failed!") ;} try {Thread.sleep;} catch (InterruptedException e) {e.printStackTrace ();} private static void initFlowRules () {List rules = new ArrayList (); FlowRule rule = new FlowRule (); rule.setResource ("sentinel-test1") Rule.setGrade (RuleConstant.FLOW_GRADE_QPS); / / Set limit QPS. Rule.setCount (1); rules.add (rule); FlowRuleManager.loadRules (rules);}} several ways to define a resource by throwing an exception define a resource / / version 1.5.0 can take advantage of the try-with-resources feature (limited use) / / resource name can use any string with business semantics, such as method name, interface name, or other uniquely identifiable string. Try (Entry entry = SphU.entry ("resourceName")) {/ / protected business logic / / do something here...} catch (BlockException ex) {/ / Resource access is blocked, restricted or degraded / / the appropriate processing operations are performed here}

* * Note: * *

If the hotspot parameter is passed in the entry, the corresponding parameter (exit (count, args)) must be included in the exit, otherwise there may be statistical errors. You can't use try-with-resources at this time.

When counting exception information through Tracer.trace (ex), the number of exceptions cannot be counted correctly because of the order of catch calls in try-with-resources syntax, so Tracer.trace (ex) can not be called in the catch block of try-with-resources when counting exception information.

Entry entry = null;// must ensure that the finally will be executed try {/ / Resource name can use any string with business semantics. Note that the number cannot be too large (more than 1K). If it exceeds several thousand, please pass it as a parameter instead of directly representing the traffic type (inbound/outbound) as the resource name / / EntryType, where the system rules only take effect on buried points of IN type entry = SphU.entry ("custom resource name"). / / protected business logic / / do something...} catch (BlockException ex) {/ / Resource access is blocked, flow is restricted or degraded / / appropriate processing operations are performed} catch (Exception ex) {/ / if you need to configure degradation rules, you need to record business exception Tracer.traceEntry (ex, entry) in this way. } finally {/ / make sure that exit is guaranteed, and that every entry and exit pair if (entry! = null) {entry.exit ();}}

Example of hotspot parameter burying:

Entry entry = null;try {/ / if you need to configure exceptions, the parameters passed in support only basic types. / / EntryType represents the traffic type, where the system rule only takes effect on the buried point of IN type. / / count is entered in most cases, which means it is counted as a call. Entry = SphU.entry (resourceName, EntryType.IN, 1, paramA, paramB); / Your logic here.} catch (BlockException ex) {/ / Handle request rejection.} finally {/ / Note: be sure to bring the corresponding parameters when exit, otherwise there may be statistical errors. If (entry! = null) {entry.exit (1, paramA, paramB) }} return Boolean value to define resource / / resource name can use any string if (SphO.entry ("custom resource name") with business semantics) {/ / make sure that finally will be executed try {/ * protected business logic * /} finally {SphO.exit () }} else {/ / Resource access is blocked, restricted, or degraded / / to perform appropriate processing operations}

* * Note: * * SphO.entry (xxx) needs to be paired with the SphO.exit () method to match the call, and the location is correct, otherwise it will cause the call chain to record an exception and throw an ErrorEntryFreeException` exception.

Annotation method defines resources / / original business methods / / configure blockHandler and fallback functions to handle @ SentinelResource (value= "resource name", blockHandler = "blockHandlerForGetUser") public User getUserById (String id) {throw new RuntimeException ("getUserById command failed");} / / blockHandler function, call public User blockHandlerForGetUser (String id, BlockException ex) {return new User ("admin") when the original method call is restricted / degraded / system protected

Detailed documentation: https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81

Asynchronous invocation defines the resource try {AsyncEntry entry = SphU.asyncEntry (resourceName); / / asynchronous invocation. DoAsync (userId, result-> {try {/ / handles the results of asynchronous calls here. } finally {/ / exit after the callback ends. Entry.exit ();}} catch (BlockException ex) {/ / Request blocked. / / Handle the exception (e.g. Retry or fallback).} types of rules flow control rules (FlowRule)

Define flow control rules through code:

Private void initFlowQpsRule () {List rules = new ArrayList (); FlowRule rule = new FlowRule (resourceName); / / set limit qps to 20 rule.setCount (20); rule.setGrade (RuleConstant.FLOW_GRADE_QPS); rule.setLimitApp ("default"); rules.add (rule); FlowRuleManager.loadRules (rules);}

* * Note: * * there can be multiple current restriction rules for the same resource at the same time, which will be checked in turn when checking the rules. Detailed reference document: https://github.com/alibaba/Sentinel/wiki/%E6%B5%81%E9%87%8F%E6%8E%A7%E5%88%B6

Fuse degradation rule (DegradeRule)

Define the circuit breaker degradation rule through the code:

Private void initDegradeRule () {List rules = new ArrayList (); DegradeRule rule = new DegradeRule (); rule.setResource (KEY); / / set threshold RT, 10 ms rule.setCount (10); rule.setGrade (RuleConstant.DEGRADE_GRADE_RT); rule.setTimeWindow (10); rules.add (rule); DegradeRuleManager.loadRules (rules);}

* * Note: * * there can be multiple downgrade rules for the same resource at the same time. Detailed reference document: https://github.com/alibaba/Sentinel/wiki/%E7%86%94%E6%96%AD%E9%99%8D%E7%BA%A7

System Protection rules (SystemRule)

Define system protection rules through code:

Private void initSystemRule () {List rules = new ArrayList (); SystemRule rule = new SystemRule (); rule.setHighestSystemLoad (10); rules.add (rule); SystemRuleManager.loadRules (rules);}

* * Note: * * system rules only apply to EntryType=IN. Detailed reference document: https://github.com/alibaba/Sentinel/wiki/%E7%B3%BB%E7%BB%9F%E8%87%AA%E9%80%82%E5%BA%94%E9%99%90%E6%B5%81

Access Control rules (AuthorityRule)

In many cases, we need to restrict whether the resource is passed according to the caller, so we can use the access control (blacklist and whitelist) feature of Sentinel. The blacklist and whitelist restricts whether the resource is passed according to the request source (origin) of the resource. If the whitelist is configured, it can only be passed if the request source is in the whitelist; if the blacklist is configured, the request source is not approved when the request source is in the blacklist, and the rest of the requests are passed. Authorization rules, that is, blacklist and whitelist rules (AuthorityRule), are very simple and have the following configuration items:

Resource: the name of the resource, that is, the object of the rule

LimitApp: corresponding blacklist / whitelist, separated by different origin, such as appA,appB

Strategy: limit mode. AUTHORITY_WHITE is whitelist mode, AUTHORITY_BLACK is blacklist mode, and default is whitelist mode. Define access control rules by code:

Private void initAuthorityRule () {AuthorityRule rule = new AuthorityRule (); rule.setResource ("test"); rule.setStrategy (RuleConstant.AUTHORITY_WHITE); rule.setLimitApp ("appA,appB"); AuthorityRuleManager.loadRules (Collections.singletonList (rule));} launch of Sentinel Dashboard console

Download the jar package from https://github.com/alibaba/Sentinel/releases and start it with the following command:

Java-Dserver.port=8080-Dcsp.sentinel.dashboard.server=localhost:8080-Dproject.name=sentinel-dashboard-jar sentinel-dashboard.jar

-Dserver.port parameter specifies console port number-Dcsp.sentinel.dashboard.server parameter specifies console service address-Dproject.name parameter specifies project name, accesses specified service address, user name and password are sentinel

Spring Boot Project connection console

Add dependencies:

Org.springframework.cloud spring-cloud-starter-alibaba-sentinel 0.9.0.RELEASE

Make a simple configuration in application.yaml:

Spring: cloud: sentinel: transport: dashboard: localhost:8080 / / console address application: name: sentinel-demo / / the name of the project in the console server: port: 9090

Interfaces that rely on automatic identification of the HTTP protocol can be seen in the cluster point link. Various rule restrictions can be made in the following action buttons.

The above is the analysis of the use of Sentinel, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report