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

How to intercept abnormal Traffic by Sentinel

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

Share

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

This article mainly introduces "how Sentinel intercepts abnormal traffic". In daily operation, I believe many people have doubts about how Sentinel intercepts abnormal traffic. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to intercept abnormal traffic by Sentinel". Next, please follow the editor to study!

In the process of using electricity at home, you must have experienced "tripping". This "gate" is used to protect our electricity when the power exceeds the load, also known as "circuit breaker", and has a loud English name-CircuitBreaker.

Like the safety of electricity, you and I should be familiar with "current limitation", "demotion" and "circuit breaker". In order not to be overwhelmed by abnormal traffic, all kinds of software, systems and Internet applications we have developed also need a circuit breaker.

In Spring applications, it is very convenient to use circuit breakers, we can use Spring Cloud CircuitBreaker.

What is Spring Cloud Circuit Breaker? If you are familiar with who Spring is, you can make a good guess. Similar to Spring Data JPA, Spring has created an abstract, standard API. This time he abstracted the "circuit breaker" about degraded fuses. With this layer, the specific implementation is who can be easily replaced, we use the code to change the basic 0.

Let's start with a preliminary impression from the official Demo:

@ RestControllerpublic class DemoController {private CircuitBreakerFactory circuitBreakerFactory; private HttpBinService httpBin; public DemoController (CircuitBreakerFactory circuitBreakerFactory, HttpBinService httpBinService) {this.circuitBreakerFactory = circuitBreakerFactory; this.httpBin = httpBinService;} @ GetMapping ("/ delay/ {seconds}") public Map delay (@ PathVariable int seconds) {return circuitBreakerFactory.create ("delay") .run (httpBin.delaySuppplier (seconds), t-> {Map fallback = new HashMap (); fallback.put ("hello", "world"); return fallback );}}

In a thousand words, I summed up a sentence like circuitBreakerFactory.create ("delay"). Run ()

Because it is abstract, there are many corresponding implementations.

Currently supported implementations are:

Hystrix

Resilience4j

Sentinel

Spring Retry

While abstraction is equivalent to setting a standard, like JDBC, whether we replace the database with MySQL,Oracle or SQLite, interfaces and other non-specific types of code do not need to be changed. The same goes for circuit breakers.

The creation method of the circuit breaker factory here is standard. Specifically here, when executing the business logic, how to intercept and degrade the circuit breaker implementation can be handed over to the specific implementation to complete.

This time, let's take the open source Sentinel as an example to see how they stop abnormal traffic.

First of all, because it is Spring Cloud, it will also be based on Spring Boot's Autoconfiguration. The following is the configuration class, and we see that a factory is generated.

Public class SentinelCircuitBreakerAutoConfiguration {@ Bean @ ConditionalOnMissingBean (CircuitBreakerFactory.class) public CircuitBreakerFactory sentinelCircuitBreakerFactory () {return new SentinelCircuitBreakerFactory ();}}

What does create come out when our actual code executes the logic?

It's a circuit breaker CircuitBreaker that executes code.

Public interface CircuitBreaker {

Default T run (Supplier toRun) {return run (toRun, throwable-> {throw new NoFallbackAvailableException ("No fallback available.", throwable);}; T run (Supplier toRun, Function fallback);}

Contains two executing methods that can specify fallback logic when needed. When it comes to Sentinel, it goes like this:

Public CircuitBreaker create (String id) {SentinelConfigBuilder.SentinelCircuitBreakerConfiguration conf = getConfigurations () .computeIfAbsent (id, defaultConfiguration); return new SentinelCircuitBreaker (id, conf.getEntryType (), conf.getRules ());}

You will see that a SentinelCircuitBreaker has been created. Our business logic will be executed in this circuit breaker, and the run method is the stage for each concrete implementation.

Override public T run (Supplier toRun, Function fallback) {Entry entry = null; try {entry = SphU.entry (resourceName, entryType); / / If the SphU.entry () does not throw `BlockException`, it means that the / / request can pass. Return toRun.get ();} catch (BlockException ex) {/ / SphU.entry () may throw BlockException which indicates that / / the request was rejected (flow control or circuit breaking triggered). / / So it should not be counted as the business exception. Return fallback.apply (ex);} catch (Exception ex) {/ / For other kinds of exceptions, we'll trace the exception count via / / Tracer.trace (ex). Tracer.trace (ex); return fallback.apply (ex);} finally {/ / Guarantee the invocation has been completed. If (entry! = null) {entry.exit ();}

OK, that's it. Spring Cloud CircuitBreaker is done. Other details are put into the concrete implementation of the "box". Now let's open this box.

Sentinel is a fuse downgrade framework, and officials introduce themselves as follows:

The highly available flow control components for distributed service architecture mainly take the flow as the starting point, and help users ensure the stability of micro-services from many dimensions, such as flow control, circuit breaker degradation, system adaptive protection and so on.

This code screenshot on the official website shows succinctly how he works.

Block in front of the business code, there is something to rush it first, can pass before taking the business logic, and all kinds of clearance is really similar.

We must all have noticed this sentence in the run method of CircuitBreaker above.

Entry = SphU.entry (resourceName, entryType)

That's the secret of all interceptions.

Whether we use the previous CircuitBreaker approach, or the @ SentinelResource annotation form, or the Interceptor approach, there is no essential difference. It's just a different trigger point. In the end, it is done through SphU.

Since it is an interception, it must be stopped to do this or that kind of inspection.

When you actually check, the core code in entry is like this:

Entry entryWithPriority (ResourceWrapper resourceWrapper,...) Throws BlockException {ProcessorSlot chain = lookProcessChain (resourceWrapper); Entry e = new CtEntry (resourceWrapper, chain, context); try {chain.entry (context, resourceWrapper,...);} catch (BlockException E1) {e.exit (count, args); throw E1;} return e;}

Note that ProcessorSlot chain = lookProcessChain (resourceWrapper) here; when the request is processed, if the processing chain is not initialized, initialize and set various first,next, and all subsequent requests will be processed according to this. All the Slot to be intercepted will be added to the chain, and then the slot in the chain will be executed one by one. Similar to Servlet Filter.

What is added to the chain?

Public class HotParamSlotChainBuilder implements SlotChainBuilder {public ProcessorSlotChain build () {ProcessorSlotChain chain = new DefaultProcessorSlotChain (); chain.addLast (new NodeSelectorSlot ()); chain.addLast (new ClusterBuilderSlot ()); chain.addLast (new LogSlot ()); chain.addLast (new StatisticSlot ()); chain.addLast (new ParamFlowSlot ()); chain.addLast (new SystemSlot ()); chain.addLast (new AuthoritySlot ()) Chain.addLast (new FlowSlot ()); chain.addLast (new DegradeSlot ()); return chain;}

Initially, first points to an anonymous inner class, and the added slot is used as the next of the chain every time addLast.

AbstractLinkedProcessorSlot end = first

@ Override public void addFirst (AbstractLinkedProcessorSlot protocolProcessor) {protocolProcessor.setNext (first.getNext ()); first.setNext (protocolProcessor); if (end = = first) {end = protocolProcessor;}} @ Override public void addLast (AbstractLinkedProcessorSlot protocolProcessor) {end.setNext (protocolProcessor); end = protocolProcessor;}

Each slot has its own specific purpose, and after dealing with its own logic, it will trigger the execution of the next slot through fireEntry.

Giving you a long thread call stack would be too obvious:

Java.lang.Thread.State: RUNNABLE at com.alibaba.csp.sentinel.slots.block.flow.FlowSlot.checkFlow (FlowSlot.java:168) at com.alibaba.csp.sentinel.slots.block.flow.FlowSlot.entry (FlowSlot.java:161) at com.alibaba.csp.sentinel.slots.block.flow.FlowSlot.entry (FlowSlot.java:139) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot.java:40) at com.alibaba.csp .sentinel.slotchain.AbstractLinkedProcessorSlot.fireentry (AbstractLinkedProcessorSlot.java:32) at com.alibaba.csp.sentinel.slots.block.authority.AuthoritySlot.entry (AuthoritySlot.java:39) at com.alibaba.csp.sentinel.slots.block.authority.AuthoritySlot.entry (AuthoritySlot.java:33) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot.java:40) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.fireEntry (AbstractLinkedProcessorSlot.java:32) at com. Alibaba.csp.sentinel.slots.system.SystemSlot.entry (SystemSlot.java:36) at com.alibaba.csp.sentinel.slots.system.SystemSlot.entry (SystemSlot.java:30) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot.java:40) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.fireEntry (AbstractLinkedProcessorSlot.java:32) at com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowSlot.entry (ParamFlowSlot.java:39) At com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowSlot.entry (ParamFlowSlot.java:33) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot.java:40) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.fireEntry (AbstractLinkedProcessorSlot.java:32) at com.alibaba.csp.sentinel.slots.statistic.StatisticSlot.entry (StatisticSlot.java:57) at com.alibaba.csp.sentinel.slots.statistic.StatisticSlot.entry (StatisticSlot) . Java: 50) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot.java:40) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.fireEntry (AbstractLinkedProcessorSlot.java:32) at com.alibaba.csp.sentinel.slots.logger.LogSlot.entry (LogSlot.java:35) at com.alibaba.csp.sentinel.slots.logger.LogSlot.entry (LogSlot.java:29) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot. Java:40) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.fireEntry (AbstractLinkedProcessorSlot.java:32) at com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot.entry (ClusterBuilderSlot.java:101) at com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot.entry (ClusterBuilderSlot.java:47) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot.java:40) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.fireEntry (AbstractLinkedProcessorSlot.java 32) at com.alibaba.csp.sentinel.slots.nodeselector.NodeSelectorSlot.entry (NodeSelectorSlot.java:171) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot.java:40) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.fireEntry (AbstractLinkedProcessorSlot.java:32) at com.alibaba.csp.sentinel.slotchain.DefaultProcessorSlotChain$1.entry (DefaultProcessorSlotChain.java:31) at com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot.transformEntry (AbstractLinkedProcessorSlot.java:40) At com.alibaba.csp.sentinel.slotchain.DefaultProcessorSlotChain.entry (DefaultProcessorSlotChain.java:75) at com.alibaba.csp.sentinel.CtSph.entryWithPriority (CtSph.java:148) at com.alibaba.csp.sentinel.CtSph.entryWithType (CtSph.java:347) at com.alibaba.csp.sentinel.CtSph.entryWithType (CtSph.java:340) at com.alibaba.csp.sentinel.SphU.entry (SphU.java:285)

There are three types of demotion

Each type will be compared according to the corresponding configuration item data. If it does not match, it will be interrupted, and it cannot be broken all the time after the interruption. When will it be restored? According to the configured time window, a recovery thread will be started, and the time will be scheduled to restore the interrupt identity.

Public boolean passCheck (Context context, DefaultNode node, int acquireCount, Object... Args) {if (cut.get ()) {return false;} ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode (this.getResource ()); if (clusterNode = = null) {return true;} if (grade = = RuleConstant.DEGRADE_GRADE_RT) {double rt = clusterNode.avgRt () If (rt < this.count) {passCount.set (0); return true;} / / Sentinel will degrade the service only if count exceeds. If (passCount.incrementAndGet () < rtSlowRequestAmount) {return true;}} else if (grade = = RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {double exception = clusterNode.exceptionQps (); double success = clusterNode.successQps (); double total = clusterNode.totalQps (); / / If total amount is less than minRequestAmount, the request will pass. If (total < minRequestAmount) {return true;} / / In the same aligned statistic time window, / / "success" (aka. Completed count) = exception count + non-exception count (realSuccess) double realSuccess = success-exception; if (realSuccess)

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