为什么80%的码农都做不了架构师?>>>   

关于pig:

基于Spring Cloud、oAuth2.0开发基于Vue前后分离的开发平台,支持账号、短信、SSO等多种登录,提供配套视频开发教程。

码云地址:https://gitee.com/log4j/pig

关于 Spring Cloud Gateway

SpringCloudGateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring云网关旨在提供一种简单而有效的路由API的方法。Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。

zuul如何实现多维度限流请参考我的博客

Zuul:构建高可用网关之多维度限流

开始Gateway 限流

POM 依赖

<!--spring cloud gateway依赖-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--基于 reactive stream 的redis -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>

配置按照请求IP 的限流

spring:cloud:gateway:routes:- id: requestratelimiter_routeuri: lb://pigx-upmsorder: 10000predicates:- Path=/admin/**filters:- name: RequestRateLimiterargs:redis-rate-limiter.replenishRate: 1  # 令牌桶的容积redis-rate-limiter.burstCapacity: 3  # 流速 每秒key-resolver: "#{@remoteAddrKeyResolver}" #SPEL表达式去的对应的bean- StripPrefix=1

配置bean,多维度限流量的入口

/**
* 自定义限流标志的key,多个维度可以从这里入手
* exchange对象中获取服务ID、请求信息,用户信息等
*/
@Bean
KeyResolver remoteAddrKeyResolver() {return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}

OK 完成。

压力测试

并发5个线程。

Redis 数据变化

我们使用redis的monitor 命令,实时查看redis 的操作情况。
会发现在redis中会操作两个key

  • request_rate_limiter.{xxx}.timestamp
  • request_rate_limiter.{xxx}.tokens

实现原理

Spring Cloud Gateway 默认实现 Redis限流,如果扩展只需要实现ratelimter接口即可。

RedisRateLimter 的核心代码,判断是否取到令牌的实现,通过调用 redis的LUA 脚本。

public Mono<Response> isAllowed(String routeId, String id) {Config routeConfig = getConfig().getOrDefault(routeId, defaultConfig);int replenishRate = routeConfig.getReplenishRate();int burstCapacity = routeConfig.getBurstCapacity();try {List<String> keys = getKeys(id);returns unixtime in seconds.List<String> scriptArgs = Arrays.asList(replenishRate + "", burstCapacity + "",Instant.now().getEpochSecond() + "", "1");// 这里是核心,执行redis 的LUA 脚本。Flux<List<Long>> flux =this.redisTemplate.execute(this.script, keys, scriptArgs);return flux.onErrorResume(throwable -> Flux.just(Arrays.asList(1L, -1L))).reduce(new ArrayList<Long>(), (longs, l) -> {longs.addAll(l);return longs;}) .map(results -> {boolean allowed = results.get(0) == 1L;Long tokensLeft = results.get(1);Response response = new Response(allowed, getHeaders(routeConfig, tokensLeft));if (log.isDebugEnabled()) {log.debug("response: " + response);}return response;});}catch (Exception e) {log.error("Error determining if user allowed from redis", e);}return Mono.just(new Response(true, getHeaders(routeConfig, -1L)));
}

LUA 脚本

转载于:https://my.oschina.net/giegie/blog/1838560

Spring Cloud Gateway 原生的接口限流该怎么玩相关推荐

  1. Spring Cloud Gateway 原生支持接口限流该怎么玩

    关于pig: 基于Spring Cloud.oAuth2.0开发基于Vue前后分离的开发平台,支持账号.短信.SSO等多种登录,提供配套视频开发教程. 关于 Spring Cloud Gateway ...

  2. Spring Cloud Gateway自带RequestRateLimiter限流应用及扩展 | Spring Cloud 16

    一.限流算法 限流是对某一时间窗口内的请求数进行限制,保持系统的可用性和稳定性,防止因流量暴增而导致的系统运行缓慢或宕机. 在开发高并发系统时有三把利器用来保护系统: 缓存:缓存的目的是提升系统访问速 ...

  3. spring gateway 限流持久化_Spring Cloud Gateway 扩展支持动态限流

    之前分享过 一篇 <Spring Cloud Gateway 原生的接口限流该怎么玩>, 核心是依赖Spring Cloud Gateway 默认提供的限流过滤器来实现 原生Request ...

  4. Spring Cloud入门-Sentinel实现服务限流、熔断与降级(Hoxton版本)

    文章目录 Spring Cloud入门系列汇总 摘要 Sentinel简介 安装Sentinel控制台 创建sentinel-service模块 限流功能 创建RateLimitController类 ...

  5. Spring自定义注解+redis实现接口限流

    在实际开发中,有时候我们需要对某些接口进行限流,防止有人恶意攻击或者是因为某些接口自身的原因,比如发短信接口,IO处理的接口. 这里我们通过自定义一个注解,并利用Spring的AOP拦截器功能来实现限 ...

  6. 实战 Spring Cloud Gateway 之限流篇

    来源:https://www.aneasystone.com/archives/2020/08/spring-cloud-gateway-current-limiting.html 话说在 Sprin ...

  7. Spring Cloud Gateway(限流)

    在高并发的应用中,限流是一个绕不开的话题.限流可以保障我们的 API 服务对所有用户的可用性,也可以防止网络攻击. 一般开发高并发系统常见的限流有:限制总并发数(比如数据库连接池.线程池).限制瞬时并 ...

  8. 【云原生微服务>SCG网关篇十二】Spring Cloud Gateway集成Sentinel API实现多种限流方式

    文章目录 一.前言 二.Gateway集成Sentinel API 0.集成Sentinel的核心概念 1)GatewayFlowRule 和 ApiDefinition 2)GatewayFlowR ...

  9. 这可能是全网Spring Cloud Gateway限流最完整的方案了!

        作者:aneasystone     https://www.aneasystone.com/ 话说在 Spring Cloud Gateway 问世之前,Spring Cloud 的微服务世 ...

最新文章

  1. OracleDBConsoleorcl服务无法启动问题(1053错误、发生服务特定错误2)
  2. tomcat出现5个using_出现急性心梗,要当心5个并发症,一个都不好惹!
  3. 数据中心的“芯”竞争
  4. [云炬创业基础笔记]做好市场调研
  5. CodeForces - 78E Evacuation(最大流)
  6. java派生类_我可以使派生类从Java的基类继承派生成员...
  7. 应该把script标签放在哪里
  8. Maven依赖的是本地工程还是仓库jar包?
  9. 管理新语:软件工作考评的设计思路
  10. python:DataFrame连续取前23列数据,或者连续取前2行数据,或者取某行某列数据
  11. c++ 各种求min/max方法效率测试
  12. VS2017透明背景和皮肤设置
  13. android旧版本运行器下载,有没有办法让新版安卓系统运行以前老安卓版本的软件?...
  14. android 分区 PT,Android:pt 、sp、dp之间的换算
  15. 公式编辑器中如何修改字体?
  16. 10大热门的物联网初创公司
  17. 用 JavaScript 和 HTML 制作一个计算器
  18. 启动Solr 8.10 后访问UI报错:CoreContainer is either not initialized or shutting down.
  19. 汽车试验数据管理(TDM系统)的特点分析及解决方案
  20. 【转】SpringMVC的工作原理图

热门文章

  1. android system 分区大小,Android System分区大小异常
  2. 计算机话筒接口,电脑麦克风插口是哪个哪位知道?
  3. 企业为什么要开通银企直联_企业为什么要把人事外包出去
  4. linux sockaddr_in头文件,linux网络编程常用头文件
  5. mysql数据库表类型设置_mysql数据库表的类型介绍
  6. 2021人工神经网络第二次作业要求
  7. 利用SeekFree的核心板调试MM32F3277的ISP功能
  8. 中波磁棒天线在接收150kHz导航信号方向性
  9. 2021年春季学期-信号与系统-第二次作业参考答案-第七小题
  10. 今天下午2:00,RT-Thread与智能车竞赛概况