This is the fourth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Sentinel Defines resource modes and resource protection rules

How resources are defined
  1. Define a resource by returning a Boolean value

The SphO provides an if-else style API to determine if a resource is being restricted. If a resource is being restricted, it returns false

if(SphO.entry("doLimiting")) {try{
                // Business logic
                log.info("{}-doLimiting",System.currentTimeMillis());
            }finally{ SphO.exit(); }}else {
            // Handle flow-controlled logic
        }
Copy the code

With this approach, be careful to call sph0.exit () after the resource is used up, otherwise the call chain records an exception and ErrorEntryFreeException is thrown

  1. Sentinel uses the @sentinelResource annotation to define resources
@SentinelResource(value = "doLimitingByAnnotation",blockHandler = "blockHandlerByName")
@RequestMapping("limit")
public void doLimitingByAnnotation(String name){
        // Business logic
        log.info("name:{}",name);
        throw new RuntimeException("doLimitingByAnnotation command failed");
}

public  void blockHandlerByName(String name,BlockException e){
        // Processing method after the current is limited
        User user = new User();
        user.setName("Gxin");
        log.info("user:{}",user.toString());
    }
Copy the code

Note:

The value blockHandlerByName method is configured for the blockHandlerByName method, which is called after the flow limiting is triggered. The definition of this method must be consistent with the return value and parameters of the original method, and the BlockException parameter should be added. Note that the blockHandler and fallback functions are used differently

3. Asynchronous call support

Sentinel supports asynchronous call link statistics

public void doLimitingByAsync(String name) {
        try {
            AsyncEntry entry = SphU.asyncEntry("doLimiting");
            CompletableFuture.runAsync(() -> {
                // The asynchronous callback performs a Context switch to get the asynchronous Context through the entry's getAsyncContext method
                ContextUtil.runOnContext(entry.getAsyncContext(), () -> {
                    try {
                        // Process the result of the asynchronous call
                        String result = entry.getAsyncContext().getName();
                        Thread.sleep(3000);
                        log.info("Async Entry Name:{}",result);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    } finally{ entry.exit(); }}); }); }catch (BlockException e) {

        }
    }
Copy the code
Sentinel resource protection rules

Sentinel supports multiple protection rules:

  • Flow control rules
  • Circuit breaker demotion rule
  • System protection rules
  • Source access control rules
  • Hotspot parameter Rules

By defining current-limiting FlowRule rules, and then use FlowRuleManager. LoadRules to load the list of rules, specific implementation is as follows

private static void initFlowRules(a){
        List<FlowRule> flowRules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        flowRule.setResource("doLimiting");
        flowRule.setCount(20);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setClusterMode(false);
        flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        flowRule.setStrategy(RuleConstant.STRATEGY_CHAIN);
        flowRule.setLimitApp("default");
        flowRules.add(flowRule);
        FlowRuleManager.loadRules(flowRules);
    }
Copy the code

The attributes of FlowRule are as follows:

  • LimitApp: indicates whether to limit streams based on call sources. The default value is default, that is, call sources are not distinguished
  • Strategy: calls relationship traffic limiting policy – direct, association, link
  • ControllerBehavior: Flow control behavior, including direct reject, queuing, and slow start modes. The default is direct reject
  • ClusterMode: Indicates whether to limit cluster traffic. The default value is no