阿里开源sentinel限流工具改造支持规则持久化

项目背景
最近遇到一个需求需要将支持进行多数据源添加,例如mysql,oracle,pg等,并且支持单表查询,跨表查询join,并且支持定义返回接口的属性。还要支持针对不同接口的限流。这里面有大概两条思路,一个思路是通过之前自研的低代码开发工具生成java类以及相关的sql还有controller,然后调用相应的编译处理,构建出来一个springboot的工程进行发布,也就是某些接口是springboot应用由他们自己连接数据库进行数据访问,另外一个思路就是进行架构拆分,可以类似于数据库设计中的执行引擎,还有解析引擎。这么做的好处在于可以节省数据库的连接资源,因为在服务增长的同事服务的增长必然要占用数据库的连接,这个是不能忽略的。所以个人更倾向于第二种方案,也能解耦。不过方案的制定不是本篇的重点,本篇还是要将sentinel用到限流中去的

至于sentinel与hystrix的区别
https://blog.csdn.net/m0_37542889/article/details/82428193这篇讲的就不错,大体意思就是sentinel更轻量也更灵活重点是这个东西比较起来hystrix更符合我一开始架构上的设计能够基于热点参数限流比较服务微服务中的HA服务间平等思想,并且能够服务我设计的模型解析引擎、执行引擎、接口,他们之间都是平等的,唯一的不同就是区别于参数。

talk is cheap ,show me the code

开始改造
sentinel分为两部分 一个是dashboard,这个能够看到我们被限流的资源情况,比如资源的列表,资源的qps,拒绝服务的统计数据。另外一个就是client,client本身就是一个埋在每个应用中的客户端,他提供与dashboard的通信,以及将dashboard中限流规则加载到客户端内存中并执行相应限流策略使用

改造步骤
因为要从源码开始改造所以要检出
https://github.com/alibaba/Sentinel.git 因为我检出时候默认的是1.8.4的快照版本,碍于稳定性所以要在本地进行tag的切换我们先改造dashboard子工程。

image.png

image.png

输入1.8.3进行稳定版本的检出。我们在稳定版本上面进行开发与改造
改造整体架构思路如下:图片来源于官方网站
image.png

1、首先是修改pom依赖
引入sentinel的zookeeper支持,并且放开zookeeper 客户端工具包curator的生效范围默认为test我们取消test

       <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-zookeeper</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


  <!--for Zookeeper rule publisher sample-->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>${curator.version}</version>
             <scope>test</scope> 删掉这行
        </dependency>

2、下面进行代码的修改
在本工程的test目录下作者已经给了改造的样例


image.png

我们将这部分代码直接拷贝到rule文件夹中


image.png

不过为了区分限流与降级配置我们对目录进行完善在原有的代码基础上zk的路径多加一层目录


image.png

image.png

3、zk连接地址的配置化改造

在作者的样例代码中给的是hardcode到代码中的配置字符串,这个我们肯定是要修改的
所以我们首先要在application.properties 增加配置项 sentinel.zkconnectstring作为我们连接zk的连接字符串配置key
然后在config目录增加ZkDatasourceConfiguration类进行配置项的读取

package com.alibaba.csp.sentinel.dashboard.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "sentinel")
public class ZkDatasourceConfiguration {
    /**
     * zk数据源是否可用
     */
    private boolean zkdatasource;
    /**
     * zk连接字符串
     */
    private String zkconnectstring;

    public boolean isZkdatasource() {
        return zkdatasource;
    }

    public void setZkdatasource(boolean zkdatasource) {
        this.zkdatasource = zkdatasource;
    }

    public String getZkconnectstring() {
        return zkconnectstring;
    }

    public void setZkconnectstring(String zkconnectstring) {
        this.zkconnectstring = zkconnectstring;
    }
}

4.改造ZookeeperConfig类将上一步的配置生效

/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.zookeeper;

import com.alibaba.csp.sentinel.dashboard.config.ZkDatasourceConfiguration;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.fastjson.JSON;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class ZookeeperConfig {
    @Autowired
    private ZkDatasourceConfiguration zkDatasourceConfiguration;
    @Bean
    public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
        return JSON::toJSONString;
    }

    @Bean
    public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, FlowRuleEntity.class);
    }

    @Bean
    @ConditionalOnProperty(prefix = "sentinel", name = "zkdatasource", havingValue = "true", matchIfMissing = false)
    public CuratorFramework zkClient() {
        CuratorFramework zkClient =
                CuratorFrameworkFactory.newClient(zkDatasourceConfiguration.getZkconnectstring(),
                        new ExponentialBackoffRetry(ZookeeperConfigUtil.SLEEP_TIME, ZookeeperConfigUtil.RETRY_TIMES));
        zkClient.start();

        return zkClient;
    }
}

5、修改FlowControllerV1类,将里面限流的相关接口改为读取或者写入zk
引入我们前面修改的限流规则的相关实现,然后修改apiQueryMachineRules方法


image.png

6、修改publishRules方法并修改相应报错内容


image.png

7、同样的方式修改DegradeController,进入降级相关的provider并修改相应逻辑
/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.controller;

import java.util.Date;
import java.util.List;

import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType;
import com.alibaba.csp.sentinel.dashboard.repository.rule.RuleRepository;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreakerStrategy;
import com.alibaba.csp.sentinel.util.StringUtil;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.domain.Result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller regarding APIs of degrade rules. Refactored since 1.8.0.
 *
 * @author Carpenter Lee
 * @author Eric Zhao
 */
@RestController
@RequestMapping("/degrade")
public class DegradeController {

    private final Logger logger = LoggerFactory.getLogger(DegradeController.class);

    @Autowired
    private RuleRepository<DegradeRuleEntity, Long> repository;
    @Autowired
    @Qualifier("degradeRuleZookeeperProvider")
    private DynamicRuleProvider<List<DegradeRuleEntity>> ruleProvider;

    @Autowired
    @Qualifier("degradeRuleZookeeperPublisher")
    private DynamicRulePublisher<List<DegradeRuleEntity>> rulePublisher;

    @GetMapping("/rules.json")
    @AuthAction(PrivilegeType.READ_RULE)
    public Result<List<DegradeRuleEntity>> apiQueryMachineRules(String app, String ip, Integer port) {
        if (StringUtil.isEmpty(app)) {
            return Result.ofFail(-1, "app can't be null or empty");
        }
        if (StringUtil.isEmpty(ip)) {
            return Result.ofFail(-1, "ip can't be null or empty");
        }
        if (port == null) {
            return Result.ofFail(-1, "port can't be null");
        }
        try {
            List<DegradeRuleEntity> rules = ruleProvider.getRules(app);
            if (rules != null && !rules.isEmpty()) {
                rules = repository.saveAll(rules);
            }
            return Result.ofSuccess(rules);
        } catch (Throwable throwable) {
            logger.error("queryApps error:", throwable);
            return Result.ofThrowable(-1, throwable);
        }
    }

    @PostMapping("/rule")
    @AuthAction(PrivilegeType.WRITE_RULE)
    public Result<DegradeRuleEntity> apiAddRule(@RequestBody DegradeRuleEntity entity) {
        Result<DegradeRuleEntity> checkResult = checkEntityInternal(entity);
        if (checkResult != null) {
            return checkResult;
        }
        Date date = new Date();
        entity.setGmtCreate(date);
        entity.setGmtModified(date);
        try {
            entity = repository.save(entity);
        } catch (Throwable t) {
            logger.error("Failed to add new degrade rule, app={}, ip={}", entity.getApp(), entity.getIp(), t);
            return Result.ofThrowable(-1, t);
        }
        if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) {
            logger.warn("Publish degrade rules failed, app={}", entity.getApp());
        }
        return Result.ofSuccess(entity);
    }

    @PutMapping("/rule/{id}")
    @AuthAction(PrivilegeType.WRITE_RULE)
    public Result<DegradeRuleEntity> apiUpdateRule(@PathVariable("id") Long id,
                                                     @RequestBody DegradeRuleEntity entity) {
        if (id == null || id <= 0) {
            return Result.ofFail(-1, "id can't be null or negative");
        }
        DegradeRuleEntity oldEntity = repository.findById(id);
        if (oldEntity == null) {
            return Result.ofFail(-1, "Degrade rule does not exist, id=" + id);
        }
        entity.setApp(oldEntity.getApp());
        entity.setIp(oldEntity.getIp());
        entity.setPort(oldEntity.getPort());
        entity.setId(oldEntity.getId());
        Result<DegradeRuleEntity> checkResult = checkEntityInternal(entity);
        if (checkResult != null) {
            return checkResult;
        }

        entity.setGmtCreate(oldEntity.getGmtCreate());
        entity.setGmtModified(new Date());
        try {
            entity = repository.save(entity);
        } catch (Throwable t) {
            logger.error("Failed to save degrade rule, id={}, rule={}", id, entity, t);
            return Result.ofThrowable(-1, t);
        }
        if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) {
            logger.warn("Publish degrade rules failed, app={}", entity.getApp());
        }
        return Result.ofSuccess(entity);
    }

    @DeleteMapping("/rule/{id}")
    @AuthAction(PrivilegeType.DELETE_RULE)
    public Result<Long> delete(@PathVariable("id") Long id) {
        if (id == null) {
            return Result.ofFail(-1, "id can't be null");
        }

        DegradeRuleEntity oldEntity = repository.findById(id);
        if (oldEntity == null) {
            return Result.ofSuccess(null);
        }

        try {
            repository.delete(id);
        } catch (Throwable throwable) {
            logger.error("Failed to delete degrade rule, id={}", id, throwable);
            return Result.ofThrowable(-1, throwable);
        }
        if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) {
            logger.warn("Publish degrade rules failed, app={}", oldEntity.getApp());
        }
        return Result.ofSuccess(id);
    }

//    private boolean publishRules(String app, String ip, Integer port) {
//        List<DegradeRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));
//        return sentinelApiClient.setDegradeRuleOfMachine(app, ip, port, rules);
//    }
    private boolean publishRules(String app, String ip, Integer port) {
        List<DegradeRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));
        try {
            rulePublisher.publish(app, rules);
        } catch (Exception e) {
            logger.error("推送降级规则失败 {}", e.getMessage(), e);
            return false;
        }
        return true;
    }

    private <R> Result<R> checkEntityInternal(DegradeRuleEntity entity) {
        if (StringUtil.isBlank(entity.getApp())) {
            return Result.ofFail(-1, "app can't be blank");
        }
        if (StringUtil.isBlank(entity.getIp())) {
            return Result.ofFail(-1, "ip can't be null or empty");
        }
        if (entity.getPort() == null || entity.getPort() <= 0) {
            return Result.ofFail(-1, "invalid port: " + entity.getPort());
        }
        if (StringUtil.isBlank(entity.getLimitApp())) {
            return Result.ofFail(-1, "limitApp can't be null or empty");
        }
        if (StringUtil.isBlank(entity.getResource())) {
            return Result.ofFail(-1, "resource can't be null or empty");
        }
        Double threshold = entity.getCount();
        if (threshold == null || threshold < 0) {
            return Result.ofFail(-1, "invalid threshold: " + threshold);
        }
        Integer recoveryTimeoutSec = entity.getTimeWindow();
        if (recoveryTimeoutSec == null || recoveryTimeoutSec <= 0) {
            return Result.ofFail(-1, "recoveryTimeout should be positive");
        }
        Integer strategy = entity.getGrade();
        if (strategy == null) {
            return Result.ofFail(-1, "circuit breaker strategy cannot be null");
        }
        if (strategy < CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType()
            || strategy > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) {
            return Result.ofFail(-1, "Invalid circuit breaker strategy: " + strategy);
        }
        if (entity.getMinRequestAmount()  == null || entity.getMinRequestAmount() <= 0) {
            return Result.ofFail(-1, "Invalid minRequestAmount");
        }
        if (entity.getStatIntervalMs() == null || entity.getStatIntervalMs() <= 0) {
            return Result.ofFail(-1, "Invalid statInterval");
        }
        if (strategy == RuleConstant.DEGRADE_GRADE_RT) {
            Double slowRatio = entity.getSlowRatioThreshold();
            if (slowRatio == null) {
                return Result.ofFail(-1, "SlowRatioThreshold is required for slow request ratio strategy");
            } else if (slowRatio < 0 || slowRatio > 1) {
                return Result.ofFail(-1, "SlowRatioThreshold should be in range: [0.0, 1.0]");
            }
        } else if (strategy == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {
            if (threshold > 1) {
                return Result.ofFail(-1, "Ratio threshold should be in range: [0.0, 1.0]");
            }
        }
        return null;
    }
}

8、另外修改所有内存存储的类内的id生成器,简单解释一下id生成器,id生成器在sentinel中是通过元子类实现的,每个rule都有自己的id,所以我们要修改所有基于内存的id生成器,我们选择的方式是用系统时间,避免下次再添加规则如果dashboard重启造成的id覆盖

//这里算是有个小bug把,规则的ID生成器如InMemDegradeRuleStore使用的是private static AtomicLong ids = new AtomicLong(0);,
    // 这样如果Dashboard重新部署的话,就会导致生成规则的id又从0开始了,这样有可能会导致新创建规则的时候,会将老规则给覆盖掉
    private static AtomicLong ids = new AtomicLong(System.currentTimeMillis());

至此就完成了dashboard的改造

自定义自己的客户端starter

为了方便后面的使用我定义了自己的基于springboot 的starter构建的逻辑也很简单,就是将zk的连接地址进行读取并且加载zk中的rule到内存中并完成基于watcher机制的规则刷新 因为本着用新不用旧的理念,使用了目前alibaba最新的版本,所以springboot 版本就来到了2.6.1,pom文件依赖如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.beagledata.brm.cloud</groupId>
    <artifactId>sentinel-client-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sentinel-client-starter</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-web-servlet</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-parameter-flow-control</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.79</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.0.1.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <distributionManagement>
        <repository>
            <id>beagledata</id>
            <name>nexus distribution snapshot repository</name>
            <url>http://192.168.100.19/nexus/content/repositories/releases</url>
        </repository>
        <snapshotRepository>
            <id>beagledata</id>
            <name>nexus distribution snapshot repository</name>
            <url>http://192.168.100.19/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>

</project>

核心类就一个将规则从zk中读出来并注册监听器

@Configuration
@EnableConfigurationProperties(ZookeeperDataSourceProperties.class)
public class ZookeeperDataSourceAutofiguration {
    @Autowired
    private ZookeeperDataSourceProperties zookeeperDataSourceProperties;
    @Value("${spring.application.name}")
    private String applicationName;
    @PostConstruct
    public void initRules() {
        // 流控规则
        final String flowPath = "/sentinel_rule_config/" + applicationName + "/flow";
        ReadableDataSource<String, List<FlowRule>> zookeeperFlowDataSource = new ZookeeperDataSource<>(zookeeperDataSourceProperties.getConnectString(), flowPath,
                source -> JSON.parseObject(source, new com.alibaba.fastjson.TypeReference<List<FlowRule>>() {
                }));
        FlowRuleManager.register2Property(zookeeperFlowDataSource.getProperty());

        // 降级规则
        final String degradePath = "/sentinel_rule_config/" + applicationName + "/degrade";
        ReadableDataSource<String, List<DegradeRule>> redisDegradeDataSource = new ZookeeperDataSource<>(zookeeperDataSourceProperties.getConnectString(), degradePath,
                source -> JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
                }));
        DegradeRuleManager.register2Property(redisDegradeDataSource.getProperty());
    }

}

整体目录结构如下


image.png

执行构建打包到自己镜像仓库中就能够在工程中使用了

搭建demo工程进行使用

pom文件中引入我们刚才构建的starter

       <dependency>
            <groupId>com.beagledata.brm.cloud</groupId>
            <artifactId>sentinel-client-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

配置文件中添加starter需要增加的配置就完成了sentinel客户端的引入

spring.application.name=demo
server.port=8088
sentinel.zk.ds.connectString=xxx.xxx.xxx.xxx:2183
spring.cloud.sentinel.eager=true
spring.cloud.sentinel.transport.port=8721    //与dashboard通信端口
spring.cloud.sentinel.transport.dashboard=127.0.0.1:8080  dashboard的地址

效果展示以及示例程序

@Service
public class TestServiceImpl implements TestService {
    @Override
    @SentinelResource(entryType = EntryType.IN,blockHandler = "block", blockHandlerClass = Block.class)
    public Object test() {
        return "hello, world";
    }

    @Override
    @SentinelResource(entryType = EntryType.IN,blockHandler = "blockHandler")
    public Object test2() {
        return "hello, world2";
    }
}

我使用的是基于注解的形式进行限流处理的,当出现限流时候对应的异常也进行了生命,这里面有个彩蛋,因为官方的sentinel没有太过详细,造成了我一开始出发规则并没有能够跑到限流处理器里面去。
关于限流处理器的说明因为web开发中经常是统一的进行接口返回,所以我使用了公用的一个类,这个类javadoc要求
handler方式得是静态方法,然而我按照他说的做并不管用,于是乎去读了源码SentinelResourceAspect#invokeResourceWithSentinel里面有一个handleBlockException

  protected Object handleBlockException(ProceedingJoinPoint pjp, SentinelResource annotation, BlockException ex)
        throws Throwable {

        // Execute block handler if configured.
        Method blockHandlerMethod = extractBlockHandlerMethod(pjp, annotation.blockHandler(),
            annotation.blockHandlerClass());
        if (blockHandlerMethod != null) {
            Object[] originArgs = pjp.getArgs();
            // Construct args.
            Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1);
            args[args.length - 1] = ex;
            return invoke(pjp, blockHandlerMethod, args);
        }

        // If no block handler is present, then go to fallback.
        return handleFallback(pjp, annotation, ex);
    }

问题就发现了作者是通过反射进行方法调用的,invoke的时候多传了一个BlockException 类型的参数,如果我的
静态方法中没有BlockException 类型的参数那么就无法进行反射调用,所以我需要在限流处理方法不仅要生命为
静态方法还有多一个BlockException 类型的参数。如下

 public static String block(BlockException exception) {
        return "blocked";
    }

enjoy it

image.png

demo工程限流效果


image.png

image.png

zookeeper中的数据存储查看是否落盘


image.png

均落盘,重启后发现限流依然生效,至此可以持久化的限流组件,且自己封装的starter就可以投入使用了。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,686评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,668评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,160评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,736评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,847评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,043评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,129评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,872评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,318评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,645评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,777评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,861评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,589评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,687评论 2 351

推荐阅读更多精彩内容