Sentinel限流

Spring Boot集成Sentinel实战

1、注意版本(springboot的版本要和sentinel的版本适配)
 

<dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        <version>2021.0.6.0</version>
</dependency>

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.15</version>

2、如果报错循环依赖

spring:
        cloud:
                sentinel:
                        filter:
                                enabled: false // 解决循环依赖报错
                        transport:
                                port: 8719
                        dashboard: localhost:8080

3、限流规则

public static void main(String[] args) {
        try {
            SpringApplication.run(PsychologyApplication.class, args);
            initSentinel();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 定义限流规则
     */
    private static void initSentinel() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("hello"); // 资源名称,限流接口注解中的value
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 根据 QPS 限流
        rule.setCount(1); // QPS 阈值【每秒只允许通过一个请求】
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT); // 调用关系限流策略【非必须设置】
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 流控效果【非必须设置】
        rule.setClusterMode(false); // 是否集群限流【非必须设置,默认非集群】
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

4、限流接口

@GetMapping(value = "/hello/{name}")
    @SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")
    public String apiHello(@PathVariable String name) {
        return "hello";
    }

    // Fallback 函数,函数签名与原函数一致或加一个 Throwable 类型的参数.
    public String helloFallback(String s) {
        return String.format("Halooooo %s", s);
    }

    // Block 异常处理函数,参数最后多一个 BlockException,其余与原函数一致.
    public String exceptionHandler(String s, BlockException ex) {
        // Do some log here.
        ex.printStackTrace();
        return "Oops, error occurred at " + s;
    }

### Sentinel 限流实现方法及配置指南 Sentinel 是一个功能强大的流量控制和熔断降级工具,适用于微服务架构中的流量控制和系统保护。它提供了灵活的限流策略和丰富的 API,支持多种限流方式,包括 QPS 限流、线程数限流以及热点参数限流等。 #### 1. 限流实现方法 Sentinel 通过定义资源和规则来实现限流。开发者可以使用 Sentinel 提供的 API 动态地定义资源,并为这些资源设置不同的限流规则。 - **定义资源** Sentinel 中的资源可以是任意的业务逻辑或接口。使用 `SphU.entry()` 方法可以对资源进行定义和保护。例如: ```java try (Entry entry = SphU.entry("resourceName")) { // 业务逻辑 } catch (BlockException ex) { // 限流或降级逻辑 } ``` 这种方式允许对特定资源进行流量控制,确保系统在高并发场景下保持稳定 [^1]。 - **限流规则配置** Sentinel 支持通过代码动态配置限流规则,也可以通过 Sentinel 控制台进行可视化配置。限流规则包括 QPS 模式、线程数模式、关联模式、链路模式等。 一个典型的限流规则配置如下: ```java List<FlowRule> rules = new ArrayList<>(); FlowRule rule = new FlowRule(); rule.setResource("resourceName"); rule.setGrade(RuleConstant.FLOW_GRADE_QPS); rule.setCount(20); rules.add(rule); FlowRuleManager.loadRules(rules); ``` 上述代码设置了资源 `"resourceName"` 的 QPS 限流规则,最大每秒请求数为 20 [^2]。 - **热点参数限流** 热点参数限流用于对某些特定参数进行限流控制,例如对某个商品 ID 的请求进行限流。可以通过 `ParamFlowRuleManager` 来配置热点参数规则: ```java ParamFlowRule rule = new ParamFlowRule("resourceName") .setParamIdx(0) .setCount(5); ParamFlowRuleManager.loadRules(Collections.singletonList(rule)); ``` 上述代码对资源 `"resourceName"` 的第一个参数进行了限流,最大每秒请求参数值相同的请求为 5 [^1]。 #### 2. 配置指南 Sentinel 支持本地配置和集群配置两种方式,适用于不同规模的系统。 - **本地限流配置** 在单机环境下,可以通过代码直接配置限流规则。例如: ```yaml spring: cloud: sentinel: transport: port: 9719 dashboard: localhost:9999 ``` 上述配置启用了 Sentinel 的监控端口,并连接到本地的 Sentinel 控制台 [^3]。 - **集群限流配置** 在分布式系统中,可以通过 Zookeeper 或 Nacos 等注册中心实现集群限流。例如,使用 Zookeeper 配置集群限流: ```yaml spring: cloud: sentinel: transport: port: 9719 dashboard: localhost:9999 application: name: appname ``` 该配置启用了 Sentinel 的集群限流功能,并将限流规则存储在 Zookeeper 中 [^3]。 - **Sentinel 控制台配置** Sentinel 提供了可视化控制台,支持动态调整限流规则。通过控制台可以实时查看资源的 QPS、线程数等指标,并根据需要调整限流阈值 [^2]。 #### 3. 限流触发后的处理 当请求超过限流规则设定的阈值时,Sentinel 会抛出 `BlockException` 异常。开发者可以通过自定义异常处理器来返回友好的提示信息或进行降级处理: ```java public class CustomBlockHandler { public static CommonResult handleBlockException() { return new CommonResult("请求过于频繁,请稍后再试", 429); } } ``` 在限流规则中可以指定该方法作为降级处理逻辑: ```java rule.setBlockHandler("handleBlockException"); rule.setBlockHandlerSource("com.example.CustomBlockHandler"); ``` --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值