SpringCloud使用Zuul限流(Zuul+Ratelimit)

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: SpringCloud使用Zuul进行限流

微服务开发中有时需要对API做限流保护,防止网络攻击,比如做一个短信验证码API,限制客户端的请求速率能在一定程度上抵御短信轰炸攻击,降低损失。微服务网关是每个请求的必经入口,非常适合做一些API限流、认证之类的操作,本文介绍Zuul如何进行限流操作,对Zuul不了解的可以参考我这篇文章:SpringCloud组件之Zuul

一、Ratelimit相关配置介绍

1、限流策略

限流粒度/类型 说明
Authenticated User 使用经过身份验证的用户名或“匿名”
Request Origin 使用用户原始请求
URL 使用下游服务的请求路径
ROLE 使用经过身份验证的用户角色
Request method 使用HTTP请求方法
Global configuration per service 这个不验证请求Origin,Authenticated User或URI,要使用这个,请不要设置type

2、可用的实现

存储类型 说明
consul 基于consul
redis 基于redis,使用时必须引入redis相关依赖
JPA 基于SpringDataJPA,需要用到数据库
MEMORY 基于本地内存,默认
BUKET4J 使用一个Java编写的基于令牌桶算法的限流库

Bucket4j实现需要相关的bean @Qualifier("RateLimit"):

  • JCache - javax.cache.Cache
  • Hazelcast - com.hazelcast.core.IMap
  • Ignite - org.apache.ignite.IgniteCache
  • Infinispan - org.infinispan.functional.ReadWriteMap

3、常见的配置属性

属性名 默认值
enabled true/false false
behind-proxy true/false false
add-response-header true/false false
key-prefix string ${spring.application.name:rate-limit-application}
repository CONSUL, REDIS, JPA, BUCKET4J_JCACHE, BUCKET4J_HAZELCAST, BUCKET4J_INFINISPAN, BUCKET4J_IGNITE -
default-policy-list list-of-policy -
policy-list Map of Lists of Policy -
postFilterOrder int FilterConstants.SEND_RESPONSE_FILTER_ORDER - 10
preFilterOrder int FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER

policy的相关属性

属性名 默认值
limit number of calls -
quota time of calls -
refresh-interval seconds 60
type [ORIGIN, USER, URL, ROLE] []

4、发生错误如何处理

  @Bean
  public RateLimiterErrorHandler rateLimitErrorHandler() {
    return new DefaultRateLimiterErrorHandler() {
        @Override
        public void handleSaveError(String key, Exception e) {
            // custom code
        }

        @Override
        public void handleFetchError(String key, Exception e) {
            // custom code
        }

        @Override
        public void handleError(String msg, Exception e) {
            // custom code
        }
    }
  }

二、搭建Zuul结合Ratelimit服务

1、导入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
    <groupId>com.marcosbarbero.cloud</groupId>
    <artifactId>spring-cloud-zuul-ratelimit</artifactId>
    <version>2.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、启动类标注解

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class ZuulRatelimitApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulRatelimitApplication.class, args);
    }
}

3、配置文件

server:
  port: 8080
spring:
  application:
    name: zuul-ratelimit
  redis:
    host: localhost
    password: 
zuul:
  # 配置路由
  routes:
    demo:
      path: /demo/**
      serviceId: demo
  # 配置限流
  ratelimit:
    enabled: true
    # 对应存储类型(用来统计存储统计信息)
    repository: redis
    # 配置路由的策略
    policy-list:
      demo:
        # 每秒允许多少个请求
        - limit: 2
          # 刷新时间(单位秒)
          refresh-interval: 1
          # 根据什么统计
          type:
            - url

4、启动后进行访问

由于我们配置的是一秒只允许两个请求,当我们超过时,会抛出过多请求异常

error

到此本文就结束啦,更多相关知识可以前往:spring-cloud-zuul-ratelimit,本demo地址:SpringCloud-Demo

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
4月前
|
算法 NoSQL API
SpringCloud&Gateway网关限流
SpringCloud&Gateway网关限流
218 7
|
3月前
|
监控 Java Sentinel
使用Sentinel进行服务调用的熔断和限流管理(SpringCloud2023实战)
Sentinel是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。
106 3
|
4月前
|
监控 Java API
Spring cloud Hystrix 、Dashboard、API(zuul)相关报错
Spring cloud Hystrix 、Dashboard、API(zuul)相关报错
50 2
|
26天前
|
Java Spring
【Azure Spring Cloud】Spring Cloud Azure 4.0 调用Key Vault遇见认证错误 AADSTS90002: Tenant not found.
【Azure Spring Cloud】Spring Cloud Azure 4.0 调用Key Vault遇见认证错误 AADSTS90002: Tenant not found.
|
1月前
|
算法 NoSQL Java
spring cloud的限流算法有哪些?
【8月更文挑战第18天】spring cloud的限流算法有哪些?
38 3
|
26天前
|
Java Spring 容器
【Azure Spring Cloud】在Azure Spring Apps上看见 App Memory Usage 和 jvm.menory.use 的指标的疑问及OOM
【Azure Spring Cloud】在Azure Spring Apps上看见 App Memory Usage 和 jvm.menory.use 的指标的疑问及OOM
|
26天前
|
存储 Java Spring
【Azure Spring Cloud】Azure Spring Cloud服务,如何获取应用程序日志文件呢?
【Azure Spring Cloud】Azure Spring Cloud服务,如何获取应用程序日志文件呢?
|
26天前
|
SQL Java 数据库连接
【Azure Spring Cloud】Azure Spring Cloud connect to SQL using MSI
【Azure Spring Cloud】Azure Spring Cloud connect to SQL using MSI
|
26天前
|
Java 开发工具 Spring
【Azure Spring Cloud】使用azure-spring-boot-starter-storage来上传文件报错: java.net.UnknownHostException: xxxxxxxx.blob.core.windows.net: Name or service not known
【Azure Spring Cloud】使用azure-spring-boot-starter-storage来上传文件报错: java.net.UnknownHostException: xxxxxxxx.blob.core.windows.net: Name or service not known
|
26天前
|
NoSQL Java Redis
【Azure Spring Cloud】Java Spring Cloud 应用部署到Azure上后,发现大量的 java.lang.NullPointerException: null at io.lettuce.core.protocol.CommandHandler.writeSingleCommand(CommandHandler.java:426) at ... 异常
【Azure Spring Cloud】Java Spring Cloud 应用部署到Azure上后,发现大量的 java.lang.NullPointerException: null at io.lettuce.core.protocol.CommandHandler.writeSingleCommand(CommandHandler.java:426) at ... 异常