詳解springboot+aop+Lua分布式限流的最佳實踐
一、什么是限流?為什么要限流?
不知道大家有沒有做過帝都的地鐵,就是進地鐵站都要排隊的那種,為什么要這樣擺長龍轉(zhuǎn)圈圈?答案就是為了限流!因為一趟地鐵的運力是有限的,一下擠進去太多人會造成站臺的擁擠、列車的超載,存在一定的安全隱患。同理,我們的程序也是一樣,它處理請求的能力也是有限的,一旦請求多到超出它的處理極限就會崩潰。為了不出現(xiàn)最壞的崩潰情況,只能耽誤一下大家進站的時間。
限流是保證系統(tǒng)高可用的重要手段!??!
由于互聯(lián)網(wǎng)公司的流量巨大,系統(tǒng)上線會做一個流量峰值的評估,尤其是像各種秒殺促銷活動,為了保證系統(tǒng)不被巨大的流量壓垮,會在系統(tǒng)流量到達一定閾值時,拒絕掉一部分流量。
限流會導(dǎo)致用戶在短時間內(nèi)(這個時間段是毫秒級的)系統(tǒng)不可用,一般我們衡量系統(tǒng)處理能力的指標(biāo)是每秒的QPS或者TPS,假設(shè)系統(tǒng)每秒的流量閾值是1000,理論上一秒內(nèi)有第1001個請求進來時,那么這個請求就會被限流。
二、限流方案
1、計數(shù)器
Java內(nèi)部也可以通過原子類計數(shù)器AtomicInteger、Semaphore信號量來做簡單的限流。
// 限流的個數(shù)
private int maxCount = 10;
// 指定的時間內(nèi)
private long interval = 60;
// 原子類計數(shù)器
private AtomicInteger atomicInteger = new AtomicInteger(0);
// 起始時間
private long startTime = System.currentTimeMillis();
public boolean limit(int maxCount, int interval) {
atomicInteger.addAndGet(1);
if (atomicInteger.get() == 1) {
startTime = System.currentTimeMillis();
atomicInteger.addAndGet(1);
return true;
}
// 超過了間隔時間,直接重新開始計數(shù)
if (System.currentTimeMillis() - startTime > interval * 1000) {
startTime = System.currentTimeMillis();
atomicInteger.set(1);
return true;
}
// 還在間隔時間內(nèi),check有沒有超過限流的個數(shù)
if (atomicInteger.get() > maxCount) {
return false;
}
return true;
}
2、漏桶算法
漏桶算法思路很簡單,我們把水比作是請求,漏桶比作是系統(tǒng)處理能力極限,水先進入到漏桶里,漏桶里的水按一定速率流出,當(dāng)流出的速率小于流入的速率時,由于漏桶容量有限,后續(xù)進入的水直接溢出(拒絕請求),以此實現(xiàn)限流。

3、令牌桶算法
令牌桶算法的原理也比較簡單,我們可以理解成醫(yī)院的掛號看病,只有拿到號以后才可以進行診病。
系統(tǒng)會維護一個令牌(token)桶,以一個恒定的速度往桶里放入令牌(token),這時如果有請求進來想要被處理,則需要先從桶里獲取一個令牌(token),當(dāng)桶里沒有令牌(token)可取時,則該請求將被拒絕服務(wù)。令牌桶算法通過控制桶的容量、發(fā)放令牌的速率,來達到對請求的限制。

4、Redis + Lua
很多同學(xué)不知道Lua是啥?個人理解,Lua腳本和 MySQL數(shù)據(jù)庫的存儲過程比較相似,他們執(zhí)行一組命令,所有命令的執(zhí)行要么全部成功或者失敗,以此達到原子性。也可以把Lua腳本理解為,一段具有業(yè)務(wù)邏輯的代碼塊。
而Lua本身就是一種編程語言,雖然redis 官方?jīng)]有直接提供限流相應(yīng)的API,但卻支持了 Lua 腳本的功能,可以使用它實現(xiàn)復(fù)雜的令牌桶或漏桶算法,也是分布式系統(tǒng)中實現(xiàn)限流的主要方式之一。
相比Redis事務(wù),Lua腳本的優(yōu)點:
- 減少網(wǎng)絡(luò)開銷: 使用Lua腳本,無需向Redis 發(fā)送多次請求,執(zhí)行一次即可,減少網(wǎng)絡(luò)傳輸
- 原子操作:Redis 將整個Lua腳本作為一個命令執(zhí)行,原子,無需擔(dān)心并發(fā)
- 復(fù)用:Lua腳本一旦執(zhí)行,會永久保存 Redis 中,,其他客戶端可復(fù)用
Lua腳本大致邏輯如下:
-- 獲取調(diào)用腳本時傳入的第一個key值(用作限流的 key)
local key = KEYS[1]
-- 獲取調(diào)用腳本時傳入的第一個參數(shù)值(限流大?。?
local limit = tonumber(ARGV[1])
-- 獲取當(dāng)前流量大小
local curentLimit = tonumber(redis.call('get', key) or "0")
-- 是否超出限流
if curentLimit + 1 > limit then
-- 返回(拒絕)
return 0
else
-- 沒有超出 value + 1
redis.call("INCRBY", key, 1)
-- 設(shè)置過期時間
redis.call("EXPIRE", key, 2)
-- 返回(放行)
return 1
end
- 通過KEYS[1] 獲取傳入的key參數(shù)
- 通過ARGV[1]獲取傳入的limit參數(shù)
- redis.call方法,從緩存中g(shù)et和key相關(guān)的值,如果為null那么就返回0
- 接著判斷緩存中記錄的數(shù)值是否會大于限制大小,如果超出表示該被限流,返回0
- 如果未超過,那么該key的緩存值+1,并設(shè)置過期時間為1秒鐘以后,并返回緩存值+1
這種方式是本文推薦的方案,具體實現(xiàn)會在后邊做細說。
5、網(wǎng)關(guān)層限流
限流常在網(wǎng)關(guān)這一層做,比如Nginx、Openresty、kong、zuul、Spring Cloud Gateway等,而像spring cloud - gateway網(wǎng)關(guān)限流底層實現(xiàn)原理,就是基于Redis + Lua,通過內(nèi)置Lua限流腳本的方式。

三、Redis + Lua 限流實現(xiàn)
下面我們通過自定義注解、aop、Redis + Lua 實現(xiàn)限流,步驟會比較詳細,為了小白能讓快速上手這里啰嗦一點,有經(jīng)驗的老鳥們多擔(dān)待一下。
1、環(huán)境準(zhǔn)備
springboot 項目創(chuàng)建地址:https://start.spring.io,很方便實用的一個工具。

2、引入依賴包
pom文件中添加如下依賴包,比較關(guān)鍵的就是 spring-boot-starter-data-redis 和 spring-boot-starter-aop。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
3、配置application.properties
在 application.properties 文件中配置提前搭建好的 redis 服務(wù)地址和端口。
spring.redis.host=127.0.0.1 spring.redis.port=6379
4、配置RedisTemplate實例
@Configuration
public class RedisLimiterHelper {
@Bean
public RedisTemplate<String, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
限流類型枚舉類
/**
* @author fu
* @description 限流類型
* @date 2020/4/8 13:47
*/
public enum LimitType {
/**
* 自定義key
*/
CUSTOMER,
/**
* 請求者IP
*/
IP;
}
5、自定義注解
我們自定義個@Limit注解,注解類型為ElementType.METHOD即作用于方法上。
period表示請求限制時間段,count表示在period這個時間段內(nèi)允許放行請求的次數(shù)。limitType代表限流的類型,可以根據(jù)請求的IP、自定義key,如果不傳limitType屬性則默認用方法名作為默認key。
/**
* @author fu
* @description 自定義限流注解
* @date 2020/4/8 13:15
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Limit {
/**
* 名字
*/
String name() default "";
/**
* key
*/
String key() default "";
/**
* Key的前綴
*/
String prefix() default "";
/**
* 給定的時間范圍 單位(秒)
*/
int period();
/**
* 一定時間內(nèi)最多訪問次數(shù)
*/
int count();
/**
* 限流的類型(用戶自定義key 或者 請求ip)
*/
LimitType limitType() default LimitType.CUSTOMER;
}
6、切面代碼實現(xiàn)
/**
* @author fu
* @description 限流切面實現(xiàn)
* @date 2020/4/8 13:04
*/
@Aspect
@Configuration
public class LimitInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class);
private static final String UNKNOWN = "unknown";
private final RedisTemplate<String, Serializable> limitRedisTemplate;
@Autowired
public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) {
this.limitRedisTemplate = limitRedisTemplate;
}
/**
* @param pjp
* @author fu
* @description 切面
* @date 2020/4/8 13:04
*/
@Around("execution(public * *(..)) && @annotation(com.xiaofu.limit.api.Limit)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Limit limitAnnotation = method.getAnnotation(Limit.class);
LimitType limitType = limitAnnotation.limitType();
String name = limitAnnotation.name();
String key;
int limitPeriod = limitAnnotation.period();
int limitCount = limitAnnotation.count();
/**
* 根據(jù)限流類型獲取不同的key ,如果不傳我們會以方法名作為key
*/
switch (limitType) {
case IP:
key = getIpAddress();
break;
case CUSTOMER:
key = limitAnnotation.key();
break;
default:
key = StringUtils.upperCase(method.getName());
}
ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));
try {
String luaScript = buildLuaScript();
RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);
logger.info("Access try count is {} for name={} and key = {}", count, name, key);
if (count != null && count.intValue() <= limitCount) {
return pjp.proceed();
} else {
throw new RuntimeException("You have been dragged into the blacklist");
}
} catch (Throwable e) {
if (e instanceof RuntimeException) {
throw new RuntimeException(e.getLocalizedMessage());
}
throw new RuntimeException("server exception");
}
}
/**
* @author fu
* @description 編寫 redis Lua 限流腳本
* @date 2020/4/8 13:24
*/
public String buildLuaScript() {
StringBuilder lua = new StringBuilder();
lua.append("local c");
lua.append("\nc = redis.call('get',KEYS[1])");
// 調(diào)用不超過最大值,則直接返回
lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
lua.append("\nreturn c;");
lua.append("\nend");
// 執(zhí)行計算器自加
lua.append("\nc = redis.call('incr',KEYS[1])");
lua.append("\nif tonumber(c) == 1 then");
// 從第一次調(diào)用開始限流,設(shè)置對應(yīng)鍵值的過期
lua.append("\nredis.call('expire',KEYS[1],ARGV[2])");
lua.append("\nend");
lua.append("\nreturn c;");
return lua.toString();
}
/**
* @author fu
* @description 獲取id地址
* @date 2020/4/8 13:24
*/
public String getIpAddress() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
7、控制層實現(xiàn)
我們將@Limit注解作用在需要進行限流的接口方法上,下邊我們給方法設(shè)置@Limit注解,在10秒內(nèi)只允許放行3個請求,這里為直觀一點用AtomicInteger計數(shù)。
/**
* @Author: fu
* @Description:
*/
@RestController
public class LimiterController {
private static final AtomicInteger ATOMIC_INTEGER_1 = new AtomicInteger();
private static final AtomicInteger ATOMIC_INTEGER_2 = new AtomicInteger();
private static final AtomicInteger ATOMIC_INTEGER_3 = new AtomicInteger();
/**
* @author fu
* @description
* @date 2020/4/8 13:42
*/
@Limit(key = "limitTest", period = 10, count = 3)
@GetMapping("/limitTest1")
public int testLimiter1() {
return ATOMIC_INTEGER_1.incrementAndGet();
}
/**
* @author fu
* @description
* @date 2020/4/8 13:42
*/
@Limit(key = "customer_limit_test", period = 10, count = 3, limitType = LimitType.CUSTOMER)
@GetMapping("/limitTest2")
public int testLimiter2() {
return ATOMIC_INTEGER_2.incrementAndGet();
}
/**
* @author fu
* @description
* @date 2020/4/8 13:42
*/
@Limit(key = "ip_limit_test", period = 10, count = 3, limitType = LimitType.IP)
@GetMapping("/limitTest3")
public int testLimiter3() {
return ATOMIC_INTEGER_3.incrementAndGet();
}
}
8、測試
測試預(yù)期:連續(xù)請求3次均可以成功,第4次請求被拒絕。接下來看一下是不是我們預(yù)期的效果,請求地址:http://127.0.0.1:8080/limitTest1,用postman進行測試,有沒有postman url直接貼瀏覽器也是一樣。

可以看到第四次請求時,應(yīng)用直接拒絕了請求,說明我們的 Springboot + aop + lua 限流方案搭建成功。

總結(jié)
以上 springboot + aop + Lua 限流實現(xiàn)是比較簡單的,旨在讓大家認識下什么是限流?如何做一個簡單的限流功能,面試要知道這是個什么東西。上面雖然說了幾種實現(xiàn)限流的方案,但選哪種還要結(jié)合具體的業(yè)務(wù)場景,不能為了用而用。
到此這篇關(guān)于詳解springboot+aop+Lua分布式限流的最佳實踐的文章就介紹到這了,更多相關(guān)springboot+aop+Lua分布式限流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實現(xiàn)二維碼生成的詳細步驟與完整代碼
如今,二維碼的應(yīng)用場景非常廣泛,從支付到信息分享,二維碼都扮演著重要角色,Spring Boot 是一個非常流行的 Java 基于 Spring 框架的微服務(wù)開發(fā)框架,它可以幫助開發(fā)者快速搭建應(yīng)用,本文將詳細介紹如何在 Spring Boot 項目中實現(xiàn)二維碼的生成,需要的朋友可以參考下2025-05-05
利用idea生成webservice客戶端超詳解步驟(wsdl文件的使用)
這篇文章主要給大家介紹了關(guān)于利用idea生成webservice客戶端超詳解步驟,第一次接觸webservice,從采坑到采坑,算是了解了一些,明白了一些,文中通過代碼以及圖文介紹的非常詳細,需要的朋友可以參考下2023-12-12
探究Java常量本質(zhì)及三種常量池(小結(jié))
這篇文章主要介紹了探究Java常量本質(zhì)及三種常量池(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Spring MVC @RequestParam注解使用場景分析
@RequestParam是Spring MVC中用于綁定HTTP查詢參數(shù)和表單數(shù)據(jù)的注解,支持類型轉(zhuǎn)換、默認值及可選參數(shù),適用于簡單數(shù)據(jù)場景,本文給大家介紹Spring MVC @RequestParam注解使用場景分析,感興趣的朋友一起看看吧2025-07-07

