zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

我司用了 6 年的 Redis 分布式限流器,可以说是非常厉害了

2023-03-14 22:20:45 时间

 一、什么是限流?为什么要限流?

不知道大家有没有做过帝都的地铁,就是进地铁站都要排队的那种,为什么要这样摆长龙转圈圈?答案就是为了 限流 !因为一趟地铁的运力是有限的,一下挤进去太多人会造成站台的拥挤、列车的超载,存在一定的安全隐患。同理,我们的程序也是一样,它处理请求的能力也是有限的,一旦请求多到超出它的处理极限就会崩溃。为了不出现最坏的崩溃情况,只能耽误一下大家进站的时间。限流是保证系统高可用的重要手段!!!

由于互联网公司的流量巨大,系统上线会做一个流量峰值的评估,尤其是像各种秒杀促销活动,为了保证系统不被巨大的流量压垮,会在系统流量到达一定阈值时,拒绝掉一部分流量。

限流会导致用户在短时间内(这个时间段是毫秒级的)系统不可用,一般我们衡量系统处理能力的指标是每秒的 QPS 或者 TPS ,假设系统每秒的流量阈值是1000,理论上一秒内有第1001个请求进来时,那么这个请求就会被限流。

二、限流方案

1、计数器
Java内部也可以通过原子类计数器 AtomicInteger 、 Semaphore 信号量来做简单的限流。

  1. // 限流的个数 
  2. private int maxCount = 10
  3. // 指定的时间内 
  4. private long interval = 60
  5. // 原子类计数器 
  6. private AtomicInteger atomicInteger = new AtomicInteger(0); 
  7. // 起始时间 
  8. private long startTime = System.currentTimeMillis(); 
  9.  
  10. public boolean limit(int maxCount, int interval) { 
  11. atomicInteger.addAndGet(1); 
  12. if (atomicInteger.get() == 1) { 
  13. startTime = System.currentTimeMillis(); 
  14. atomicInteger.addAndGet(1); 
  15. return true
  16. // 超过了间隔时间,直接重新开始计数 
  17. if (System.currentTimeMillis() - startTime > interval * 1000) { 
  18. startTime = System.currentTimeMillis(); 
  19. atomicInteger.set(1); 
  20. return true
  21. // 还在间隔时间内,check有没有超过限流的个数 
  22. if (atomicInteger.get() > maxCount) { 
  23. return false
  24. return true

2、漏桶算法

漏桶算法思路很简单,我们把水比作是 请求 ,漏桶比作是 系统处理能力极限 ,水先进入到漏桶里,漏桶里的水按一定速率流出,当流出的速率小于流入的速率时,由于漏桶容量有限,后续进入的水直接溢出(拒绝请求),以此实现限流。

3、令牌桶算法

令牌桶算法的原理也比较简单,我们可以理解成医院的挂号看病,只有拿到号以后才可以进行诊病。

系统会维护一个令牌( token )桶,以一个恒定的速度往桶里放入令牌( token ),这时如果有请求进来想要被处理,则需要先从桶里获取一个令牌( token ),当桶里没有令牌( token)可取时,则该请求将被拒绝服务。令牌桶算法通过控制桶的容量、发放令牌的速率,来达到对请求的限制。

4、Redis + Lua

很多同学不知道 Lua 是啥?个人理解, Lua 脚本和 MySQL 数据库的存储过程比较相似,他们执行一组命令,所有命令的执行要么全部成功或者失败,以此达到原子性。也可以把 Lua 脚本理解为,一段具有业务逻辑的代码块。

而 Lua 本身就是一种编程语言,虽然 redis 官方没有直接提供限流相应的 API ,但却支持了Lua 脚本的功能,可以使用它实现复杂的令牌桶或漏桶算法,也是分布式系统中实现限流的主要方式之一。

相比 Redis 事务, Lua脚本 的优点:

  1. 减少网络开销:使用 Lua 脚本,无需向 Redis 发送多次请求,执行一次即可,减少网络传输
  2. 原子操作: Redis 将整个 Lua 脚本作为一个命令执行,原子,无需担心并发
  3. 复用: Lua 脚本一旦执行,会永久保存 Redis 中,,其他客户端可复用

Lua 脚本大致逻辑如下:

  1. -- 获取调用脚本时传入的第一个key值(用作限流的 key) 
  2. local key = KEYS[1
  3. -- 获取调用脚本时传入的第一个参数值(限流大小) 
  4. local limit = tonumber(ARGV[1]) 
  5.  
  6. -- 获取当前流量大小 
  7. local curentLimit = tonumber(redis.call('get', key) or "0"
  8.  
  9. -- 是否超出限流 
  10. if curentLimit + 1 > limit then 
  11. -- 返回(拒绝) 
  12. return 0 
  13. else 
  14. -- 没有超出 value + 1 
  15. redis.call("INCRBY", key, 1
  16. -- 设置过期时间 
  17. redis.call("EXPIRE", key, 2
  18. -- 返回(放行) 
  19. return 1 
  20. end 
  • 通过 KEYS[1] 获取传入的key参数
  • 通过 ARGV[1] 获取传入的 limit 参数
  • redis.call方法,从缓存中get和key相关的值,如果为null那么就返回0
  • 接着判断缓存中记录的数值是否会大于限制大小,如果超出表示该被限流,返回0
  • 如果未超过,那么该key的缓存值+1,并设置过期时间为1秒钟以后,并返回缓存值+1

这种方式是本文推荐的方案,具体实现会在后边做细说。

5、网关层限流

限流常在网关这一层做,比如 Nginx 、 Openresty 、 kong 、 zuul 、 Spring Cloud Gateway 等,而像 spring cloud - gateway 网关限流底层实现原理,就是基于 Redis + Lua ,通过内置 Lua 限流脚本的方式。

三、Redis + Lua 限流实现

下面我们通过 自定义注解 、 aop 、 Redis + Lua 实现限流,步骤会比较详细,为了小白能让快速上手这里啰嗦一点,有经验的老鸟们多担待一下。

1、环境准备

springboot 项目创建地址:https://start.spring.io,很方便实用的一个工具。

2、引入依赖包

pom文件中添加如下依赖包,比较关键的就是 spring-boot-starter-data-redis 和 spring-boot-starter-aop 。

  1. <dependencies> 
  2.       <dependency> 
  3.           <groupId>org.springframework.boot</groupId> 
  4.           <artifactId>spring-boot-starter-web</artifactId> 
  5.       </dependency> 
  6.       <dependency> 
  7.           <groupId>org.springframework.boot</groupId> 
  8.           <artifactId>spring-boot-starter-data-redis</artifactId> 
  9.       </dependency> 
  10.       <dependency> 
  11.           <groupId>org.springframework.boot</groupId> 
  12.           <artifactId>spring-boot-starter-aop</artifactId> 
  13.       </dependency> 
  14.       <dependency> 
  15.           <groupId>com.google.guava</groupId> 
  16.           <artifactId>guava</artifactId> 
  17.           <version>21.0</version> 
  18.       </dependency> 
  19.       <dependency> 
  20.           <groupId>org.springframework.boot</groupId> 
  21.           <artifactId>spring-boot-starter-test</artifactId> 
  22.       </dependency> 
  23.       <dependency> 
  24.           <groupId>org.apache.commons</groupId> 
  25.           <artifactId>commons-lang3</artifactId> 
  26.       </dependency> 
  27.  
  28.       <dependency> 
  29.           <groupId>org.springframework.boot</groupId> 
  30.           <artifactId>spring-boot-starter-test</artifactId> 
  31.           <scope>test</scope> 
  32.           <exclusions> 
  33.               <exclusion> 
  34.                   <groupId>org.junit.vintage</groupId> 
  35.                   <artifactId>junit-vintage-engine</artifactId> 
  36.               </exclusion> 
  37.           </exclusions> 
  38.       </dependency> 
  39.   </dependencies> 

3、配置application.properties

在 application.properties 文件中配置提前搭建好的 redis 服务地址和端口。

  1. spring.redis.host=127.0.0.1 
  2.  
  3. spring.redis.port=6379 

4、配置RedisTemplate实例

  1. @Configuration 
  2. public class RedisLimiterHelper { 
  3.  
  4.     @Bean 
  5.     public RedisTemplate<String, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) { 
  6.         RedisTemplate<String, Serializable> template = new RedisTemplate<>(); 
  7.         template.setKeySerializer(new StringRedisSerializer()); 
  8.         template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); 
  9.         template.setConnectionFactory(redisConnectionFactory); 
  10.         return template; 
  11.     } 

限流类型枚举类

  1. /** 
  2.  * @author fu 
  3.  * @description 限流类型 
  4.  * @date 2020/4/8 13:47 
  5.  */ 
  6. public enum LimitType { 
  7.  
  8.     /** 
  9.      * 自定义key 
  10.      */ 
  11.     CUSTOMER, 
  12.  
  13.     /** 
  14.      * 请求者IP 
  15.      */ 
  16.     IP; 

5、自定义注解

我们自定义个 @Limit 注解,注解类型为 ElementType.METHOD 即作用于方法上。

period 表示请求限制时间段, count 表示在 period 这个时间段内允许放行请求的次数。 limitType 代表限流的类型,可以根据 请求的IP 、 自定义key ,如果不传 limitType 属性则默认用方法名作为默认key。

  1. /** 
  2.  * @author fu 
  3.  * @description 自定义限流注解 
  4.  * @date 2020/4/8 13:15 
  5.  */ 
  6. @Target({ElementType.METHOD, ElementType.TYPE}) 
  7. @Retention(RetentionPolicy.RUNTIME) 
  8. @Inherited 
  9. @Documented 
  10. public @interface Limit { 
  11.  
  12.     /** 
  13.      * 名字 
  14.      */ 
  15.     String name() default ""
  16.  
  17.     /** 
  18.      * key 
  19.      */ 
  20.     String key() default ""
  21.  
  22.     /** 
  23.      * Key的前缀 
  24.      */ 
  25.     String prefix() default ""
  26.  
  27.     /** 
  28.      * 给定的时间范围 单位(秒) 
  29.      */ 
  30.     int period(); 
  31.  
  32.     /** 
  33.      * 一定时间内最多访问次数 
  34.      */ 
  35.     int count(); 
  36.  
  37.     /** 
  38.      * 限流的类型(用户自定义key 或者 请求ip) 
  39.      */ 
  40.     LimitType limitType() default LimitType.CUSTOMER; 

6、切面代码实现

  1. /** 
  2.  * @author fu 
  3.  * @description 限流切面实现 
  4.  * @date 2020/4/8 13:04 
  5.  */ 
  6. @Aspect 
  7. @Configuration 
  8. public class LimitInterceptor { 
  9.  
  10.     private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class); 
  11.  
  12.     private static final String UNKNOWN = "unknown"
  13.  
  14.     private final RedisTemplate<String, Serializable> limitRedisTemplate; 
  15.  
  16.     @Autowired 
  17.     public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) { 
  18.         this.limitRedisTemplate = limitRedisTemplate; 
  19.     } 
  20.  
  21.     /** 
  22.      * @param pjp 
  23.      * @author fu 
  24.      * @description 切面 
  25.      * @date 2020/4/8 13:04 
  26.      */ 
  27.     @Around("execution(public * *(..)) && @annotation(com.xiaofu.limit.api.Limit)"
  28.     public Object interceptor(ProceedingJoinPoint pjp) { 
  29.         MethodSignature signature = (MethodSignature) pjp.getSignature(); 
  30.         Method method = signature.getMethod(); 
  31.         Limit limitAnnotation = method.getAnnotation(Limit.class); 
  32.         LimitType limitType = limitAnnotation.limitType(); 
  33.         String name = limitAnnotation.name(); 
  34.         String key; 
  35.         int limitPeriod = limitAnnotation.period(); 
  36.         int limitCount = limitAnnotation.count(); 
  37.  
  38.         /** 
  39.          * 根据限流类型获取不同的key ,如果不传我们会以方法名作为key 
  40.          */ 
  41.         switch (limitType) { 
  42.             case IP: 
  43.                 key = getIpAddress(); 
  44.                 break
  45.             case CUSTOMER: 
  46.                 key = limitAnnotation.key(); 
  47.                 break
  48.             default
  49.                 key = StringUtils.upperCase(method.getName()); 
  50.         } 
  51.  
  52.         ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key)); 
  53.         try { 
  54.             String luaScript = buildLuaScript(); 
  55.             RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class); 
  56.             Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod); 
  57.             logger.info("Access try count is {} for name={} and key = {}", count, name, key); 
  58.             if (count != null && count.intValue() <= limitCount) { 
  59.                 return pjp.proceed(); 
  60.             } else { 
  61.                 throw new RuntimeException("You have been dragged into the blacklist"); 
  62.             } 
  63.         } catch (Throwable e) { 
  64.             if (e instanceof RuntimeException) { 
  65.                 throw new RuntimeException(e.getLocalizedMessage()); 
  66.             } 
  67.             throw new RuntimeException("server exception"); 
  68.         } 
  69.     } 
  70.  
  71.     /** 
  72.      * @author fu 
  73.      * @description 编写 redis Lua 限流脚本 
  74.      * @date 2020/4/8 13:24 
  75.      */ 
  76.     public String buildLuaScript() { 
  77.         StringBuilder lua = new StringBuilder(); 
  78.         lua.append("local c"); 
  79.         lua.append("\nc = redis.call('get',KEYS[1])"); 
  80.         // 调用不超过最大值,则直接返回 
  81.         lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then"); 
  82.         lua.append("\nreturn c;"); 
  83.         lua.append("\nend"); 
  84.         // 执行计算器自加 
  85.         lua.append("\nc = redis.call('incr',KEYS[1])"); 
  86.         lua.append("\nif tonumber(c) == 1 then"); 
  87.         // 从第一次调用开始限流,设置对应键值的过期 
  88.         lua.append("\nredis.call('expire',KEYS[1],ARGV[2])"); 
  89.         lua.append("\nend"); 
  90.         lua.append("\nreturn c;"); 
  91.         return lua.toString(); 
  92.     } 
  93.  
  94.  
  95.     /** 
  96.      * @author fu 
  97.      * @description 获取id地址 
  98.      * @date 2020/4/8 13:24 
  99.      */ 
  100.     public String getIpAddress() { 
  101.         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
  102.         String ip = request.getHeader("x-forwarded-for"); 
  103.         if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 
  104.             ip = request.getHeader("Proxy-Client-IP"); 
  105.         } 
  106.         if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 
  107.             ip = request.getHeader("WL-Proxy-Client-IP"); 
  108.         } 
  109.         if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 
  110.             ip = request.getRemoteAddr(); 
  111.         } 
  112.         return ip; 
  113.     } 

7、控制层实现

我们将@Limit注解作用在需要进行限流的接口方法上,下边我们给方法设置@Limit注解,在10秒内只允许放行3个请求,这里为直观一点用AtomicInteger计数。

  1. /** 
  2.  * @Author: fu 
  3.  * @Description: 
  4.  */ 
  5. @RestController 
  6. public class LimiterController { 
  7.  
  8.     private static final AtomicInteger ATOMIC_INTEGER_1 = new AtomicInteger(); 
  9.     private static final AtomicInteger ATOMIC_INTEGER_2 = new AtomicInteger(); 
  10.     private static final AtomicInteger ATOMIC_INTEGER_3 = new AtomicInteger(); 
  11.  
  12.     /** 
  13.      * @author fu 
  14.      * @description 
  15.      * @date 2020/4/8 13:42 
  16.      */ 
  17.     @Limit(key = "limitTest", period = 10, count = 3
  18.     @GetMapping("/limitTest1"
  19.     public int testLimiter1() { 
  20.  
  21.         return ATOMIC_INTEGER_1.incrementAndGet(); 
  22.     } 
  23.  
  24.     /** 
  25.      * @author fu 
  26.      * @description 
  27.      * @date 2020/4/8 13:42 
  28.      */ 
  29.     @Limit(key = "customer_limit_test", period = 10, count = 3, limitType = LimitType.CUSTOMER) 
  30.     @GetMapping("/limitTest2"
  31.     public int testLimiter2() { 
  32.  
  33.         return ATOMIC_INTEGER_2.incrementAndGet(); 
  34.     } 
  35.  
  36.     /** 
  37.      * @author fu 
  38.      * @description  
  39.      * @date 2020/4/8 13:42 
  40.      */ 
  41.     @Limit(key = "ip_limit_test", period = 10, count = 3, limitType = LimitType.IP) 
  42.     @GetMapping("/limitTest3"
  43.     public int testLimiter3() { 
  44.  
  45.         return ATOMIC_INTEGER_3.incrementAndGet(); 
  46.     } 
  47.  

8、测试

测试 「预期」 :连续请求3次均可以成功,第4次请求被拒绝。接下来看一下是不是我们预期的效果,请求地址: http://127.0.0.1:8080/limitTest1 ,用 postman 进行测试,有没有 postman url直接贴浏览器也是一样。

可以看到第四次请求时,应用直接拒绝了请求,说明我们的 Springboot + aop + lua 限流方案搭建成功。

以上 springboot + aop + Lua 限流实现是比较简单的,旨在让大家认识下什么是限流?如何做一个简单的限流功能,面试要知道这是个什么东西。上面虽然说了几种实现限流的方案,但选哪种还要结合具体的业务场景,不能为了用而用。