redis实现网关限流限制API调用次数1000次分

21次阅读

共计 1628 个字符,预计需要花费 5 分钟才能阅读完成。

  1. 添加 maven 依赖,使用 springboot2.x 版本
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
  1. 添加 redis 配置进 application.yml,springboot2.x 版本的 redis 是使用 lettuce 配置的
spring:
  redis:
    database: 0
    host: localhost
    port: 6379
    lettuce:                  # 这里标明使用 lettuce 配置
      pool:
        max-active: 8         # 连接池最大连接数
        max-wait: -1ms        # 连接池最大阻塞等待时间 ( 使用负值表示没有限制
        max-idle: 5           # 连接池中的最大空闲连接
        min-idle: 0           # 连接池中的最小空闲连接
    timeout: 10000ms          # 连接超时时间 
  1. 使用 redis 作限流器有两种写法

方法一:

        Long size = redisTemplate.opsForList().size("apiRequest");
        if (size < 1000) {redisTemplate.opsForList().leftPush("apiRequest", System.currentTimeMillis());
        } else {Long start = (Long) redisTemplate.opsForList().index("apiRequest", -1);
            if ((System.currentTimeMillis() - start) < 60000) {throw new RuntimeException("超过限流阈值");
            } else {redisTemplate.opsForList().leftPush("apiRequest", System.currentTimeMillis());
                redisTemplate.opsForList().trim("apiRequest", -1, -1);
            }
        }

核心思路:用一个 list 来存放一串值,每次请求都把当前时间放进,如果列表长度为 1000,那么调用就是 1000 次。如果第 1000 次调用时的当前时间和最初的时间差小于 60s,那么就是 1 分钟里调用超 1000 次。否则,就清空列表之前的值

方法二:

        Integer count = (Integer) redisTemplate.opsForValue().get("apiKey");
        Integer integer = Optional.ofNullable(count).orElse(0);
        if (integer > 1000) {throw new RuntimeException("超过限流阈值");
        }
        if (redisTemplate.getExpire("apiKey", TimeUnit.SECONDS).longValue() < 0) {redisTemplate.multi();
            redisTemplate.opsForValue().increment("apiKey", 1);
            redisTemplate.expire("apiKey", 60, TimeUnit.SECONDS);
            redisTemplate.exec();} else {redisTemplate.opsForValue().increment("apiKey", 1);
        }

核心思路:设置 key,过期时间为 1 分钟,其值是 api 这分钟内调用次数

对比:方法一耗内存,限流准确。方法二结果有部分误差,只限制 key 存在的这一分钟内调用次数低于 1000 次,不代表任意时间段的一分钟调用次数低于 1000

正文完
 0