SpringCloudAlibabaSentinel实现网关动态限流

gateway集成阿里Sentinel后,控制台如何根据url动态限流 gateway网关集成Sentinel后,控制台默认限流是根据服务进行的,默认为资源名为ReactiveCompositeDiscoveryClient_服务名称,如下图: 所以限流都是根据整个服务进行的,那么如何像单机一样根据url分组限流呢;有两种方式: 1.通过初始化配置: @Configuration public class SentinelInitUrlConfig { @PostConstruct public void doInit() { lo 阅读详情

目录

1.SpringCloudAlibabaSentinel实现网关动态限流

1.概念和来历

2.概览及控制台搭建

3.控制台有哪些能力

4.功能及设计理念

5.限流的几种方法

2.SpringCloud Alibaba Sentinel 的降级功能

1.yml中添加配置

2.编写配置类

3.编写兜底工具类

3.Sentinel还对Feigin实现了适配,支持Fenig的容错降级

3.1启动类添加注解

3.2编写feign接口

3.3编写Sentinel 对 OpenFeign 接口的降级策略

4.Sentinel结合Nacos实现限流规则持久化

4.1sentinel存储在nacos中限流数据结构

4.2添加依赖

4.3在限流资源添加限流规则

4.4在yml文件中添加配置

5.GeteWay集成Sentinel实现网关限流

5.1最简单、也是常用的测试方式:在网关内硬编码实现对请求的限流

5.2配置文件的方式编写限流规则

5.3Gateway集成Nacos+Sentiel实现网关动态限流

6.为什么需要限流


1.SpringCloudAlibabaSentinel实现网关动态限流

1.概念和来历

Sentinel 是面向分布式服务架构的流量控制组件,主要以流量为切入点,从流量控制、熔断降级、系统自适应保护等多个维度来帮助您保障微服务的稳定性。
Sentinel的来历
1.2012年,Sentinel 诞生,主要功能为入口流量控制
2.2013-2017 年,Sentinel 在阿里巴巴集团内部迅速发展,成为基础技术模块,覆盖了所有的核心场景
3.2018 年,Sentinel 开源,并持续演进
​
SpringCloud Alibaba Sentinel 的基本概念
资源:可以是 Java 应用程序中的任何内容,例如,由应用程序提供的服务,或由应用程序调用的其它应用提供的服务,甚至可以是一段代码
方法签名 URL 服务名
规则:围绕资源的实时状态设定的规则,可以包括流量控制规则、熔断降级规则以及系统保护规则:且所有规则可以动态实时调整

2.概览及控制台搭建

Sentinel提供一个轻量级的开源控制台(单机和集群),规则管理和推送的功能
获取并启动 Sentinel Dashboard (控制台
​
1.下载控制台 Jar 包: https://github.com/alibaba/Sentinel/releases
# 创建命令
mkdir -p /usr/local/sentinel
​
cd  /usr/local/sentinel
#下载1.8.0版本
wget https://github.com/alibaba/Sentinel/releases/download/1.8.1/sentinel-dashboard-1.8.1.jar
​
2.nohup  java -Dserver.port=7777 -Dcsp.sentinel.dashboard.server=localhost:7777 -Dproject.name=butool-sentinel-dashboard -jar /usr/local/sentinel/sentinel-dashboard-1.8.1.jar &
​
3.从Sentinel 1.6.0 起,Sentinel Dashboard 引入了基本的登录功能,默认的用户名密码都是 sentinel
​
4.打开防火墙端口
firewall-cmd --zone=public --add-port=7777/tcp --permanent
firewall-cmd --reload
​
4.访问地址
ip:7777

3.控制台有哪些能力

1.查看机器列表以及健康情况: 收集 Sentinel 客户端发送的心跳包,用于判断机器是否在线
​
2.监控(单机和集群聚合): 通过 Sentinel 客户端暴露的监控 API,定期拉取并且聚合应用监控信息,最终可以实现秒级的实时监控
​
3.规则管理和推送:统一管理推送规则

4.功能及设计理念

4.1流量控制

流量控制在网络传输中是一个常用的概念,
它用于调整网络包的发送数据。
然而,从系统稳定性角度考虑,
在处理请求的速度上,也有非常多的讲究。
任意时间到来的请求往往是随机不可控的,
而系统的处理能力是有限的。
我们需要根据系统的处理能力对流量进行控制。
Sentinel 作为一个调配器,可以根据需要把随机的请求调整成合适的形状,
如下图所示:

4.2流量控制设计理念

流量控制有以下几个角度:
​
1.资源的调用关系,例如资源的调用链路,资源和资源之间的关系;
​
2.运行指标,例如 QPS、线程池、系统负载等;
​
3.控制的效果,例如直接限流、冷启动、排队等。
​
Sentinel 的设计理念是让您自由选择控制的角度,并进行灵活组合,从而达到想要的效果。

5.限流的几种方法

1.硬编码方式

1.yml文件里添加sentinel服务端地址
2.在资源方法上添加注解@SentinelResource(value="方法名")
3.配置初始化方法指定资源为SentinelResource.value
4.设置一秒请求几次
5.完成请求
6.控制台可以看到流控资源列表,看不到可能懒加载就请求一次

2.设置自定义返回信息

1.在controller中添加方法,返回值和Request方法一致,入参为BlockException
2.获取错误信息BlockException.getRuleLimitApp()
3.@SentinelResource注解中添加属性flowHandle值为方法名称
4.连续请求两次会看到结果

3.自定义通用的限流逻辑

1.创建类类中需要写静态方法,sentinel不会对对象进行new操作 
2.方法返回值和Request方法一致,入参为BlockException
3.获取错误信息BlockException.getRuleLimitApp()
4.@SentinelResource注解中添加属性flowHandleClass值为类名,@SentinelResource.bolckHandler值为静态方法名称

4.基于sentinel控制台配置流控规则,根据资源名称

1.sentinel懒加载需要请求一次就会在控制台上看到资源
2.定义controller方法在控制台新增流控规则根据资源名称
@SentinelResource(
value ="byResource",blockHandler ="qinyiHandleBlockException"blockHandlerClass = ButoolBlockHandler.class
public CommonResponse<String> byResource() {}
请求一次后在控制台配置限流规则

5.在“簇点链路”中给 url 添加流控规则

在“簇点链路”中给 url 添加流控规则
@SentinelResource(value = "byUrl")public CommonResponse<String> byUrl{}
在控制台簇点链路中新增流控规则

2.SpringCloud Alibaba Sentinel 的降级功能

1.Sentinel 支持对 RestTemplate 服务调用进行保护,实现流控降级和异常降级
2.在构造RestTempplate这bean上添加@SentinelRestTemplate注解

1.yml中添加配置

# 开启或关闭 @SentinelRestTemplate 注解
resttemplate:
  sentinel:
    enabled: true

2.编写配置类

package cn.butool.conf;
​
import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
​
/**
 * <h1>开启服务间的调用保护, 需要给 RestTemplate 做一些包装</h1>
 * */
@Slf4j
@Configuration
public class SentinelConfig {
​
    /**
     * <h2>包装 RestTemplate</h2>
     * */
    @Bean
//    @SentinelRestTemplate(
//            fallback = "handleFallback", fallbackClass = RestTemplateExceptionUtil.class,
//            blockHandler = "handleBlock", blockHandlerClass = RestTemplateExceptionUtil.class
//    )
    public RestTemplate restTemplate() {
        return new RestTemplate();  // 可以对其做一些业务相关的配置
    }
}
​

3.编写兜底工具类

package cn.butool.conf;
​
import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.imooc.ecommerce.vo.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
​
/**
 * <h1>RestTemplate 在限流或异常时的兜底方法</h1>
 * */
@Slf4j
public class RestTemplateExceptionUtil {
​
    /**
     * <h2>限流后的处理方法</h2>
     * */
    public static SentinelClientHttpResponse handleBlock(HttpRequest request,
                                                         byte[] body,
                                                         ClientHttpRequestExecution execution,
                                                         BlockException ex) {
        log.error("Handle RestTemplate Block Exception: [{}], [{}]",
                request.getURI().getPath(), ex.getClass().getCanonicalName());
        return new SentinelClientHttpResponse(
                JSON.toJSONString(new JwtToken("butool-block"))
        );
    }
​
    /**
     * <h2>异常降级之后的处理方法</h2>
     * */
    public static SentinelClientHttpResponse handleFallback(HttpRequest request,
                                                            byte[] body,
                                                            ClientHttpRequestExecution execution,
                                                            BlockException ex) {
        log.error("Handle RestTemplate Fallback Exception: [{}], [{}]",
                request.getURI().getPath(), ex.getClass().getCanonicalName());
        return new SentinelClientHttpResponse(
                JSON.toJSONString(new JwtToken("butool-block"))
        );
    }
}
​

3.Sentinel还对Feigin实现了适配,支持Fenig的容错降级

## 打开 Sentinel 对 Feign 的支持
feign:
  sentinel:
    enabled: true

3.1启动类添加注解

@EnableFeignClients

3.2编写feign接口

/**
 * <h1>通过 Sentinel 对 OpenFeign 实现熔断降级</h1>
 * */
@FeignClient(
        value = "e-commerce-butool",
        fallback = SentinelFeignClientFallback.class
)
public interface SentinelFeignClient {
​
    @RequestMapping(value = "busl", method = RequestMethod.GET)
    CommonResponse<String> getResultByFeign(@RequestParam Integer code);
}
​

3.3编写Sentinel 对 OpenFeign 接口的降级策略

​
import cn.butool.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
​
/**
 * <h1>Sentinel 对 OpenFeign 接口的降级策略</h1>
 * */
@Slf4j
@Component
public class SentinelFeignClientFallback implements SentinelFeignClient {
​
    @Override
    public CommonResponse<String> getResultByFeign(Integer code) {
​
        log.error("request supply for test has some error: [{}]", code);
        return new CommonResponse<>(
                -1,
                "sentinel feign fallback",
                "input code: "+ code
        );
    }
}

4.Sentinel结合Nacos实现限流规则持久化

1.Sentinel Dashboard 将规则保存在内存中,重启之后就会丢失,所以,考虑使用外部持久化方案
2.在Nacos 中创建规则,Nacos 会推送到客户端,Sentinel Dashboard 也会从 Nacos 去获取配置信息(远程配置中心(e.g. Nacos, ZooKeeper))

4.1sentinel存储在nacos中限流数据结构

[
  {
    "resource": "byResource", # 资源名
    "limitApp": "default", # 流控针对的调用来源
    "grade": 1, # 限流的阈值类型 1 QPS ,0 并发线程数
    "count": 3, # 每1秒中能通过几个请求
    "strategy": 0, # 0 直接限流 1 关联 2 链路
    "controlBehavior": 0, # 控制效果:0 快速失败 1 warm Up 2 排队等待
    "clusterMode": false # 是否集群效果
  }
]

4.2添加依赖

 <!-- Sentinel 使用 Nacos 存储规则 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>

4.3在限流资源添加限流规则

/**
     * <h2>在 dashboard 中 "流控规则" 中按照资源名称新增流控规则</h2>
     * */
    @GetMapping("/by-resource")
    @SentinelResource(
            value = "byResource",
            blockHandler = "ButoolHandleBlockException",
            blockHandlerClass = ButoolBlockHandler.class
    )
    public CommonResponse<String> byResource() {
        log.info("coming in rate limit controller by resource");
        return new CommonResponse<>(0, "", "byResource");
    }
package cn.butool.block_handler;
​
import cn.butool.vo.CommonResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
​
/**
 * <h1>自定义通用的限流处理逻辑</h1>
 * */
@Slf4j
public class ButoolBlockHandler {
​
    /**
     * <h2>通用限流处理方法</h2>
     * 这个方法必须是 static 的
     * */
    public static CommonResponse<String> ButoolHandleBlockException(BlockException exception) {
​
        log.error("trigger qinyi block handler: [{}], [{}]",
                JSON.toJSONString(exception.getRule()), exception.getRuleLimitApp());
        return new CommonResponse<>(
                -1,
                "flow rule trigger block exception",
                null
        );
    }
}
​

4.4在yml文件中添加配置

datasource:
        # 名称任意, 代表数据源
        ds:
          nacos:
            # NacosDataSourceProperties.java 中定义
            server-addr: ${spring.cloud.nacos.discovery.server-addr}
            dataId: ${spring.application.name}-sentinel
            namespace: ${spring.cloud.nacos.discovery.namespace}
            groupId: DEFAULT_GROUP
            data-type: json
            # 规则类型: com.alibaba.cloud.sentinel.datasource.RuleType
            # FlowRule 就是限流规则
            rule-type: flow
      # 服务启动直接建立心跳连接
      eager: true

5.GeteWay集成Sentinel实现网关限流

5.1最简单、也是常用的测试方式:在网关内硬编码实现对请求的限流

[
​
  {
    "resource": "nacos-client-api",
    "resourceMode": 1, # 规则与resource相绑定
    "count": 1, # 限流阈值
    "Grade": 1, # 限流的阈值类型 1 QPS ,0 并发线程数
    "intervalSec": 60 # 统计范围 60秒内允许1个请求
  }
]
​

1网关服务添加依赖

<!-- 集成 Sentinel, 在网关层面实现限流 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
        </dependency>
        <!-- Sentinel 使用 Nacos 存储规则 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>

2yml中添加配置

sentinel: # 与nacos属性平齐
      # 配置 sentinel dashboard 地址
      transport:
        dashboard: 192.168.1.11:7777
        clientIp: 192.168.1.7
        port: 8719 # 会在应用对应的机器上启动一个 Http Server, 该 Server 会与 Sentinel 控制台做交互
  

3sentinel服务端启动命令修改

# 支持网关
nohup java -Dcsp.sentinel.app.type=1 -Dserver.port=7777 -Dcsp.sentinel.dashboard.server=localhost:7777 -Dproject.name=butool-sentinel-gateway -jar /usr/local/sentinel/sentinel-dashboard-1.8.1.jar &

4网关集成配置类

package cn.butool.config;
​
 import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
​
import javax.annotation.PostConstruct;
import java.util.*;
​
/**
 * <h1>Gateway 集成 Sentinel 实现限流</h1>
 * */
@Slf4j
@Configuration
public class SentinelGatewayConfiguration {
​
    /** 视图解析器 */
    private final List<ViewResolver> viewResolvers;
    /** HTTP 请求和响应数据的编解码配置 */
    private final ServerCodecConfigurer serverCodecConfigurer;
​
    /**
     * <h2>构造方法</h2>
     * */
    public SentinelGatewayConfiguration(
            ObjectProvider<List<ViewResolver>> viewResolversProvider,
            ServerCodecConfigurer serverCodecConfigurer
    ) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }
​
    /**
     * <h2>限流异常处理器, 限流异常出现时, 执行到这个 handler</h2>
     * */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // 默认会返回错误 message, code 429
        return new SentinelGatewayBlockExceptionHandler(
                this.viewResolvers,
                this.serverCodecConfigurer
        );
    }
​
    /**
     * <h2>限流过滤器, 是 Gateway 全局过滤器, 优先级定义为最高</h2>
     * */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }
​
    /**
     *
     * 初始化限流规则
     * */
    @PostConstruct
    public void doInit(){
​
        log.info("--------------------------------------");
        log.info("load sentinel gateway rules (code define)");
        initGatewayRules();
        log.info("--------------------------------------");
    }
    /**
     * 硬编码网关限流规则
     */
    private void initGatewayRules(){
        Set<GatewayFlowRule> rules = new HashSet<>();
​
        GatewayFlowRule rule = new GatewayFlowRule();
        // 指定限流模式, 根据 route_id 做限流, 默认的模式
        rule.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID);
        // 指定 route_id -> service id
        rule.setResource("e-commerce-nacos-client");
        // 按照 QPS 限流
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 统计窗口和限流阈值
        rule.setIntervalSec(60);
        rule.setCount(3);
​
        rules.add(rule);
​
       
        // 加载到网关中
        GatewayRuleManager.loadRules(rules);
​
       
    }
}
​

4请求指定的服务查看限流情况

 // 指定 route_id -> service id rule.setResource("e-commerce-nacos-client"); 60秒内请求三次以上报下面错误

5自定义返回错误信息

/**
     *
     * 初始化限流规则
     * */
    @PostConstruct
    public void doInit(){
​
        log.info("--------------------------------------");
        log.info("load sentinel gateway rules (code define)");
        initGatewayRules();
        log.info("--------------------------------------");
​
        // 加载自定义限流异常处理器
        initBlockHandler();
    }
​
​
/**
     * <h2>自定义限流异常处理器</h2>
     * */
    private void initBlockHandler() {
​
        // 自定义 BlockRequestHandler
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange,
                                                      Throwable throwable) {
                log.error("------------- trigger gateway sentinel rule -------------");
                Map<String, String> result = new HashMap<>();
                result.put("code", String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value()));
                result.put("message", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
                result.put("route", "e-commerce-nacos-client");
                return ServerResponse
                        .status(HttpStatus.TOO_MANY_REQUESTS)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(result));
            }
        };
        // 设置自定义限流异常处理器
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

6.自定义分组限流

​
    
/**
     * 硬编码网关限流规则
     */
    private void initGatewayRules(){
        Set<GatewayFlowRule> rules = new HashSet<>();
        // 限流分组, Sentinel 先去找规则定义, 再去找规则中定义的分组
        rules.add(
                new GatewayFlowRule("nacos-client-api-1")
                        .setCount(3).setIntervalSec(60)
        );
        rules.add(
                new GatewayFlowRule("nacos-client-api-2")
                        .setCount(1).setIntervalSec(60)
        );
        // 加载到网关中
        GatewayRuleManager.loadRules(rules);
        // 加载限流分组
        initCustomizedApis();
    }
​
   
​
    /**
     * <h2>硬编码网关限流分组</h2>
     * 1. 最大限制 - 演示
     * 2. 具体的分组
     * */
    private void initCustomizedApis() {
​
        Set<ApiDefinition> definitions = new HashSet<>();
​
        // nacos-client-api 组, 最大的限制
        ApiDefinition api = new ApiDefinition("nacos-client-api")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    // 模糊匹配 /butool/ecommerce-nacos-client/ 及其子路径的所有请求
                    add(new ApiPathPredicateItem()
                            .setPattern("/butool/ecommerce-nacos-client/**")
                            // 根据前缀匹配
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
​
        // nacos-client-api-1 分组
        ApiDefinition api1 = new ApiDefinition("nacos-client-api-1")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem()
                            // 精确匹配 /butool/ecommerce-nacos-client/nacos-client/service-instance
                            .setPattern("/butool/ecommerce-nacos-client/nacos-client/service-instance"));
                }});
​
        // nacos-client-api-2 分组
        ApiDefinition api2 = new ApiDefinition("nacos-client-api-2")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem()
                            // 精确匹配 /butool/ecommerce-nacos-client/nacos-client/project-config
                            .setPattern("/butool/ecommerce-nacos-client" +
                                    "/nacos-client/project-config"));
                }});
​
        definitions.add(api1);
        definitions.add(api2);
​
        // 加载限流分组
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }

5.2配置文件的方式编写限流规则

1.yml文件

硬编码工作较多,相对来说比较繁琐;熟悉之后可以进一步使用配置文件的形式
1.resources目录下存放文件
2.yml文件中配置
    sentinel:
      # 配置 sentinel dashboard 地址
      transport:
        dashboard: 192.168.1.11:7777
        clientIp: 192.168.1.7
        port: 8719 # 会在应用对应的机器上启动一个 Http Server, 该 Server 会与 Sentinel 控制台做交互
      datasource:
       #通过本地文件方式, 基于服务级别的配置
        dsl.file:
          file: classpath:gateway-flow-rule-sentinel.json
          # 代表服务级别的限流, 一步步点进去看, 文件类型
          ruleType: gw-flow
        # 通过本地文件方式, 细粒度对指定 api 进行配置
        ds2.file:
          file: classpath:gateway-flow-rule-api-sentinel.json
          # 代表 API 分组, 一步步点进去看, 文件类型
          ruleType: gw-api-group  

2.json文件

## 文件名 gateway-flow-rule-api-sentinel.json
[
  {
    "apiName": "nacos-client-api",
    "predicateItems": [
      {
        "pattern": "/butool/ecommerce-nacos-client/nacos-client/project-config"
      },
      {
        "pattern": "/butool/ecommerce-nacos-client/**",
        "matchStrategy": 1
      }
    ]
  }
]
​
## 文件名 gateway-flow-rule-sentinel.json
[
  {
    "resource": "e-commerce-nacos-client",
    "resourceMode": 0,
    "count": 3,
    "intervalSec": 60
  },
  {
    "resource": "nacos-client-api",
    "resourceMode": 1,
    "count": 1,
    "intervalSec": 60
  }
]
​

5.配置类

package cn.butool.config;
​
import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
​
import javax.annotation.PostConstruct;
import java.util.*;
​
/**
 * <h1>Gateway 集成 Sentinel 实现限流</h1>
 * */
@Slf4j
@Configuration
public class SentinelGatewayConfiguration {
​
    /** 视图解析器 */
    private final List<ViewResolver> viewResolvers;
    /** HTTP 请求和响应数据的编解码配置 */
    private final ServerCodecConfigurer serverCodecConfigurer;
​
    /**
     * <h2>构造方法</h2>
     * */
    public SentinelGatewayConfiguration(
            ObjectProvider<List<ViewResolver>> viewResolversProvider,
            ServerCodecConfigurer serverCodecConfigurer
    ) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }
​
    /**
     * <h2>限流异常处理器, 限流异常出现时, 执行到这个 handler</h2>
     * */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // 默认会返回错误 message, code 429
        return new SentinelGatewayBlockExceptionHandler(
                this.viewResolvers,
                this.serverCodecConfigurer
        );
    }
​
    /**
     * <h2>限流过滤器, 是 Gateway 全局过滤器, 优先级定义为最高</h2>
     * */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }
}
​

5.3Gateway集成Nacos+Sentiel实现网关动态限流

1.nacos中添加配置

2.json内容

## dataId gateway-flow-rule-api-sentinel
[
  {
    "apiName": "nacos-client-api",
    "predicateItems": [
      {
        "pattern": "/butool/ecommerce-nacos-client/nacos-client/project-config"
      },
      {
        "pattern": "/butool/ecommerce-nacos-client/**",
        "matchStrategy": 1
      }
    ]
  }
]
​
## dataId gateway-flow-rule-sentinel
[
  {
    "resource": "e-commerce-nacos-client",
    "resourceMode": 0,
    "count": 3,
    "intervalSec": 60
  },
  {
    "resource": "nacos-client-api",
    "resourceMode": 1,
    "count": 1,
    "intervalSec": 60
  }
]
​

6.为什么需要限流

1.平台用户增长过快 
​2.热点事件、热点接口、热点 Key ​ 
3.恶意请求
​

1.实现原理

Sentinel 通过实现 Filter,对路由/API分组匹配、请求属性解析和参数组装实现限流

【开源】Sentinel高性能高可用集群限流解决方案 Sentinel集群限流的高性能高可用解决方案。通过接入协调集群和实现容错策略解决其单点故障问题;支持动态集群限流,单节点可支撑千万业务流量;支持资源路由让Token Server节点资源能够得到充分的利用.... 阅读详情

相关推荐

限流及及常用解决方案

限流及及常用解决方案

小胡子 732

只需三步实现Gateway结合Sentinel实现无侵入网关限流,注意避坑!

本文基于您已有基础的可运行的微服务系统,使用了Sping Cloud Alibaba,Gateway,Nacos等;目标实现网关流控类型的限流。顾名思义限流用于在高并发场景下限制请求流量的进入,保护系统不被冲垮。阿里巴巴的开源sentinel可以通过设置不同种类规则实现对不同的资源的保护。

mxt51220的博客 3371

SAP生产版本导入避坑大全:从‘黄灯’到‘绿灯’,详解CM_FV_MKAL_CONSISTENCY_CHECK检查函数

本文深入解析SAP生产版本导入过程中的常见问题,特别是通过`CM_FV_MKAL_CONSISTENCY_CHECK`检查函数从‘黄灯’异常到‘绿灯’正常的修复方法。涵盖静态与动态校验机制、典型异常场景诊断及批量导入最佳实践,帮助SAP运维人员高效解决生产版本管理难题。

weixin_30568591的博客 385

springcloud gateway网关动态配置限流

这里简单记录一下gateway网关集成mybatisPlus实现动态限流。gateway网关默认的限流方式各项限流参数都是在配置文件中配置,不够灵活,虽然使用阿里的Sentinel组件可以实现从nacos注册中心、配置中心动态读取配置,但是还是有一定的局限性。

Muscleheng的博客 2230

Pyrosim进阶指南:从隧道火灾模拟到复杂通风策略分析

本文深入探讨Pyrosim在隧道火灾模拟与通风策略分析中的高级应用。从精确几何建模到火源参数设置,再到通风系统的量化分析,详细介绍了如何利用Pyrosim优化隧道安全设计。特别强调了临界风速验证、横向通风配置及结果可视化技巧,为工程师提供实用的进阶指南。

weixin_30644369的博客 137

手把手教你用单结晶体管搭建简易振荡电路(含电路图和波形分析)

本文详细介绍了如何使用单结晶体管(UJT)搭建简易振荡电路,包括电路设计、波形分析和实战技巧。通过具体的电路图和参数计算,帮助电子爱好者和工程师快速掌握UJT振荡器的设计与调试方法,适用于脉冲信号生成和时钟源制作等应用场景。

weixin_29207533的博客 515

Sentinel 网关流量控制之Spring Cloud Gateway实战

点击左上角蓝字,关注“锅外的大佬”专注分享国外最新技术内容学习本篇文章之前如果你还没有了解过Sentinel是什么的话,请先学习一下分布式系统的流量防卫兵Sentinel...

liululee的博客 1万+

thinkphp5.0.24反序列化漏洞分析

深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!因此收集整理了一份《Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

m0_67392182的博客 1871

spring cloud alibaba开发笔记十四(SpringCloud Alibaba Sentinel)

SpringCloud Alibaba Sentinel的概念 ◆Sentinel 是面向分布式服务架构的流量控制组件,主要以流量为切入点,从流量控制、熔断降级、系统自适应保护等多个维度来帮助您保障微服务的稳定性

qq_41054749的博客 880

2、探秘储备池计算:原理、应用与前沿趋势

储备池计算(Reservoir Computing)作为一种新兴的计算方法,起源于计算神经科学和机器学习领域,现已广泛应用于非线性动力系统理论、物理学、材料科学、生物学和机器人学等多个领域。其核心优势在于概念简洁性,通过利用高维动态系统的非线性响应,将学习过程集中在读出层,避免了传统循环神经网络(RNN)训练的复杂性。储备池计算的发展方向主要包括拓展到非线性动态系统和利用物理动态系统作为计算资源(PRC),后者有望突破冯·诺依曼瓶颈,实现边缘计算。理论方面,储备池计算与人类大脑的信息处理方式密切相关,并推动

ggg99的专栏 729

【HALCON工业视觉应用探索】10. C#+Halcon 3D视觉实战:点云处理与三维测量工业指南(附完整代码与实操案例)

摘要:本文聚焦C#+Halcon在3D视觉领域的工业应用,从新手友好的“基础3D检测系统”切入,逐步深入“汽车铸件三维测量”等工业级场景。内容涵盖核心概念(点云数据结构、3D采集原理、坐标系统)、完整技术流程(数据采集→预处理→特征提取→三维测量→结果可视化)、工业级代码实现(多视角点云融合、微缺陷检测、高精度尺寸测量),以及现场落地关键技巧(硬件选型、标定流程、抗干扰优化)。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 2004

SpringCloud Alibaba 之 Gateway 集成 Sentinel;SPI机制

SPI(Service Provider Interface)是一种Java提供的用来动态发现和加载服务接口实现的机制。在Spring Cloud Alibaba Sentinel中,通过SPI的方式提供了对不同框架的支持,包括对Spring Cloud Gateway的支持。当你引入了Sentinel Gateway的相关依赖后,Sentinel会自动注册一个SPI实现类到Spring Cloud Gateway的过滤器链中,该过滤器会根据Sentinel控制台定义的规则来进行限流、熔断等操作。

qq_33240556的博客 810

【第一章】基于Simulink的控制器开发教程——目录

摘要:本文系统介绍了基于Simulink的控制器开发方法,涵盖PID、状态反馈、模型预测(MPC)、模糊控制、自适应控制等8类主流控制器。针对每种控制器,详细阐述了其基本原理、适用场景,并通过Simulink建模与仿真测试进行实践验证。文章采用"理论+实践"的结构,从算法设计到硬件实现全流程展开,为汽车、航空航天、工业控制等领域的控制器开发提供完整解决方案,最后通过应用对比与学习总结帮助读者掌握不同控制器的核心特性和应用场景。(149字)

熟悉MATLAB/fpga/RK3588/LABVIEW/protus/单片机/dsp/Multisim 385

SpringCloud高级应用-Gateway

淘汰的技术组件的替换方案上面英文大概意思是:Eureka2.0 的开源工作已经停止,依赖于开源库里面的 Eureka 2.x 分支构建的项目或者相关代码,风险自负。Eureka在微服务项目中主要承担服务注册与发现工作,可以替代的技术方案比较多,而且很多方案都比Eureka优秀,比如Consul、Nacos等。Hystrix在项目中主要做服务熔断、降级,但官方宣布将不在开发,目前处于维护状态,但官方表示 1.5.18 版本的 Hystrix 已经足够稳定,可以满足 Netflix 现有应用的需求。

沉浸式Study 2002

OPPO 数据分析面试题及参考答案

如何设计共享单车数据库的各个字段? 对于共享单车的数据库设计,首先考虑用户相关的字段。用户表可以包含用户 ID,这是一个唯一标识符,用于区分不同用户;姓名,记录用户的真实姓名;联系方式,比如手机号码,方便在出现问题时联系用户;注册时间,记录用户何时开始使用共享单车服务;信用分数,用于衡量用户使用共享单车过程中的行为是否合规,比如是否按时归还车辆等。 车辆信息表要有车辆 ID,这是车辆的唯一标识;车辆类型,例如普通单车、电动单车等;投放时间,即车辆投放到市场的时间;车辆状态,包括是否可用(如正

大模型大数据攻城狮的专栏 1182

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Spring Cloud Alibaba Sentinel 的流量控制规则有哪些?

这些规则可以通过 Sentinel 控制台进行配置和管理,也可以通过编程的方式动态地添加、修改或删除规则。通过 Sentinel Dashboard 或者通过编写代码的方式,可以方便地定义和管理上述提到的各种流量控制规则。Spring Cloud Alibaba Sentinel 是一个用于高并发系统的流量控制、熔断降级、系统防护等场景的开源框架。Sentinel 提供了丰富的流量控制策略,这些策略可以用来保护下游服务免受突发流量的影响,确保系统的稳定性和响应性。

qq_33240556的博客 471

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

微服务SpringCloud相关组件

一、SpringCloud的相关组件 1、 Eureka 一个基于 REST 服务的,服务注册与发现的组件,它主要包括两个组件:Eureka Server 和 Eureka Client。 2、 Ribbon 主要是用于实现负载均衡,可配合服务发现和断路器使用。 3、 Hystrix 熔断器,容错管理工具,通过熔断机制控制服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。 4、 Zuul Zuul网关,在云平台上提供动态路由,监控,弹性,安全等边缘服务的框架。 Zuul 相当于是设备和 Netfl

xiaohui的博客 346

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Sentinel 集群「限流」探索

最近看了下关于分布式限流的部分,看到Sentinel的分布式限流,也就是集群限流的部分,想搭个环境看看,结果发现网上关于这方面的内容基本可以说没有,你甚至很难跑起来他的demo,就算能跑起来,估计也得自己研究半天,麻烦的要死。我猜测很重要的原因可能就是Sentinel关于这块做的并不完善,而且从官方的Issue中能看出来,其实官方对于这块后续并没有计划去做的更好。那么废话不多说,在此之前,肯定要先说下关于Sentinel集群限流方面的原理,没有原理一切都是空中楼阁。

程序员高级码农的博客 1776

Spring Cloud Gateway 限流

一般开发高并发系统常见的限流有:限制总并发数(比如数据库连接池、线程池)、限制瞬时并发数(如 nginx 的 limit_conn 模块,用来限制瞬时并发连接数)、限制时间窗口内的平均速率(如 Guava 的 RateLimiter、nginx 的 limit_req 模块,限制每秒的平均速率);此做法被认为没有很好的处理单位时间的边界,比如在前一秒的最后一毫秒里和下一秒的第一毫秒都触发了最大的请求数,也就是在两毫秒内发生了两倍的 TPS。一旦需要提高速率,则按需提高放入桶中的令牌的速率。

提供各种学习资源及帮助 2732

Sentinel 动态流控规则

Sentinel 动态流控规则 SPI扩展 集群限流

杨宇昌的博客 2728

Nacos+Sentinel+gateway 实现微服务限流

Nacos+Sentinel+gateway 实现微服务限流

chenfang8712的专栏 3196

Spring Cloud Gateway 整合阿里 Sentinel网关限流实战

xx

梦想起飞的地方......... 1156

Gateway整合Sentinel实现对路由的限流规则

在限流或者熔断后,我们肯定不能直接返回这个异常给前端,接下来就进行自定义异常返回结果在Gateway网关服务中添加一个配置类/**自定义异常处理*@Author胡尚*@Date50//1.创建一个BlockRequestHandler对象,它是一个接口,所以就需要匿名内部类BlockRequestHandlerblockRequestHandler=newBlockRequestHandler(){springcloud。...

qq_44027353的博客 2589

微服务 过滤器 集成Sentinel实现网关限流

微服务学习笔记

m0_62434717的博客 5973

springcloud(gateway限流)

目录。

m0_64863860的博客 1862

微服务限流Sentinel讲解(四)

3.隔离和降级 限流是一种预防措施,虽然限流可以尽量避免因高并发而引起的服务故障,但服务还会因为其它原因而故障。 而要将这些故障控制在一定范围,避免雪崩,就要靠线程隔离(舱壁模式)和熔断降级手段了。 线程隔离之前讲到过:调用者在调用服务提供者时,给每个调用的请求分配独立线程池,出现故障时,最多消耗这个线程池内资源,避免把调用者的所有资源耗尽。 熔断降级:是在调用方这边加入断路器,统计对服务提供者的调用,如果调用的失败比例过高,则熔断该业务,不允许访问该服务的提供者了。 可以..

软件开发实战项目分享 1182
上一篇: 电脑组装配件知识
下一篇: springCloud统一响应、全局异常处理
别浪呀
博客等级 码龄8年 1万+粉丝 260原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值