- 添加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>
- 添加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 # 連接超時時間
- 使用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