01.07 Java併發:分佈式應用限流 Redis + Lua 實踐


Java併發:分佈式應用限流 Redis + Lua 實踐

任何限流都不是漫無目的的,也不是一個開關就可以解決的問題,常用的限流算法有:令牌桶,漏桶。在之前的文章中,也講到過,但是那是基於單機場景來寫。

之前文章:接口限流算法:漏桶算法&令牌桶算法

然而再牛逼的機器,再優化的設計,對於特殊場景我們也是要特殊處理的。就拿秒殺來說,可能會有百萬級別的用戶進行搶購,而商品數量遠遠小於用戶數量。如果這些請求都進入隊列或者查詢緩存,對於最終結果沒有任何意義,徒增後臺華麗的數據。對此,為了減少資源浪費,減輕後端壓力,我們還需要對秒殺進行限流,只需保障部分用戶服務正常即可。

就秒殺接口來說,當訪問頻率或者併發請求超過其承受範圍的時候,這時候我們就要考慮限流來保證接口的可用性,以防止非預期的請求對系統壓力過大而引起的系統癱瘓。通常的策略就是拒絕多餘的訪問,或者讓多餘的訪問排隊等待服務。

分佈式限流

單機限流,可以用到 AtomicInteger、RateLimiter、Semaphore 這些。但是在分佈式中,就不能使用了。常用分佈式限流用 Nginx 限流,但是它屬於網關層面,不能解決所有問題,例如內部服務,短信接口,你無法保證消費方是否會做好限流控制,所以自己在應用層實現限流還是很有必要的。

本文不涉及 Nginx + Lua ,簡單介紹 Redis + Lua 分佈式限流的實現。如果是需要在接入層限流的話,應該直接採用nginx自帶的連接數限流模塊和請求限流模塊。

Redis + Lua 限流示例

本次項目使用SpringBoot 2.0.4,使用到 Redis 集群,Lua 限流腳本

引入依賴

<code><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>org.apache.commons/<groupid>
<artifactid>commons-lang3/<artifactid>
/<dependency>
<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-test/<artifactid>
/<dependency>

/<dependencies>/<code>

Redis 配置

application.properties

<code>spring.application.name=spring-boot-limit

# Redis數據庫索引
spring.redis.database=0
# Redis服務器地址
spring.redis.host=10.4.89.161
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=-1
# 連接池中的最大空閒連接
spring.redis.jedis.pool.max-idle=8
# 連接池中的最小空閒連接
spring.redis.jedis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=10000/<code>

Lua 腳本

參考: 聊聊高併發系統之限流特技
http://jinnianshilongnian.iteye.com/blog/2305117

<code>local key = "rate.limit:" .. KEYS[1] --限流KEY
local limit = tonumber(ARGV[1]) --限流大小
local current = tonumber(redis.call('get', key) or "0")

if current + 1 > limit then --如果超出限流大小
return 0
else --請求數+1,並設置2秒過期
redis.call("INCRBY", key,"1")
redis.call("expire", key,"2")
return current + 1
end/<code>

1、我們通過KEYS[1] 獲取傳入的key參數
2、通過ARGV[1]獲取傳入的limit參數
3、redis.call方法,從緩存中get和key相關的值,如果為nil那麼就返回0
4、接著判斷緩存中記錄的數值是否會大於限制大小,如果超出表示該被限流,返回0
5、如果未超過,那麼該key的緩存值+1,並設置過期時間為1秒鐘以後,並返回緩存值+1

限流注解

註解的目的,是在需要限流的方法上使用

<code>package com.souyunku.example.annotation;
/**
* 描述: 限流注解
*
* @author yanpenglei
* @create 2018-08-16 15:24
**/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {

/**
* 限流唯一標示
*
* @return
*/

String key() default "";

/**
* 限流時間
*
* @return
*/
int time();

/**
* 限流次數
*
* @return
*/
int count();
}/<code>

公共配置

<code>package com.souyunku.example.config;

@Component
public class Commons {

/**
* 讀取限流腳本
*
* @return
*/
@Bean
public DefaultRedisScript<number> redisluaScript() {
DefaultRedisScript<number> redisScript = new DefaultRedisScript<>();
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimit.lua")));
redisScript.setResultType(Number.class);
return redisScript;
}

/**
* RedisTemplate
*
* @return
*/
@Bean
public RedisTemplate<string> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<string> template = new RedisTemplate<string>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;

}

}/<string>/<string>/<string>/<number>/<number>/<code>

攔截器

通過攔截器 攔截@RateLimit註解的方法,使用Redsi execute 方法執行我們的限流腳本,判斷是否超過限流次數

以下下是核心代碼

<code>package com.souyunku.example.config;

/**
* 描述:攔截器
*
* @author yanpenglei
* @create 2018-08-16 15:33
**/
@Aspect
@Configuration
public class LimitAspect {

private static final Logger logger = LoggerFactory.getLogger(LimitAspect.class);

@Autowired
private RedisTemplate<string> limitRedisTemplate;

@Autowired
private DefaultRedisScript<number> redisluaScript;

@Around("execution(* com.souyunku.example.controller ..*(..) )")
public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {

MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Class> targetClass = method.getDeclaringClass();
RateLimit rateLimit = method.getAnnotation(RateLimit.class);

if (rateLimit != null) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ipAddress = getIpAddr(request);

StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(ipAddress).append("-")
.append(targetClass.getName()).append("- ")

.append(method.getName()).append("-")
.append(rateLimit.key());

List<string> keys = Collections.singletonList(stringBuffer.toString());

Number number = limitRedisTemplate.execute(redisluaScript, keys, rateLimit.count(), rateLimit.time());

if (number != null && number.intValue() != 0 && number.intValue() <= rateLimit.count()) {
logger.info("限流時間段內訪問第:{} 次", number.toString());
return joinPoint.proceed();
}

} else {
return joinPoint.proceed();
}

throw new RuntimeException("已經到設置限流次數");
}

public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
// 對於通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress = "";
}
return ipAddress;
}
}/<string>/<number>/<string>/<code>

控制層

添加 @RateLimit() 註解,會在 Redsi 中生成 10 秒中,可以訪問5次 的key

RedisAtomicLong 是為測試例子例,記錄累計訪問次數,跟限流沒有關係。

<code>package com.souyunku.example.controller;

/**
* 描述: 測試頁
*
* @author yanpenglei
* @create 2018-08-16 15:42
**/
@RestController
public class LimiterController {

@Autowired
private RedisTemplate redisTemplate;

// 10 秒中,可以訪問10次
@RateLimit(key = "test", time = 10, count = 10)
@GetMapping("/test")
public String luaLimiter() {
RedisAtomicInteger entityIdCounter = new RedisAtomicInteger("entityIdCounter", redisTemplate.getConnectionFactory());

String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");

return date + " 累計訪問次數:" + entityIdCounter.getAndIncrement();
}
}/<code>

啟動服務

<code>package com.souyunku.example;

@SpringBootApplication
public class SpringBootLimitApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootLimitApplication.class, args);
}
}/<code>

啟動項目頁面訪問:http://127.0.0.1:8080/test

10 秒中,可以訪問10次,超過十次,頁面就報錯,等夠10秒,重新計算。

後臺日誌

<code>2018-08-16 18:41:08.205  INFO 18076 --- [nio-8080-exec-1] com.souyunku.example.config.LimitAspect  : 限流時間段內訪問第:1 次
2018-08-16 18:41:08.426 INFO 18076 --- [nio-8080-exec-3] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:2 次
2018-08-16 18:41:08.611 INFO 18076 --- [nio-8080-exec-5] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:3 次
2018-08-16 18:41:08.819 INFO 18076 --- [nio-8080-exec-7] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:4 次
2018-08-16 18:41:09.021 INFO 18076 --- [nio-8080-exec-9] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:5 次
2018-08-16 18:41:09.203 INFO 18076 --- [nio-8080-exec-1] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:6 次
2018-08-16 18:41:09.406 INFO 18076 --- [nio-8080-exec-3] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:7 次
2018-08-16 18:41:09.629 INFO 18076 --- [nio-8080-exec-5] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:8 次
2018-08-16 18:41:09.874 INFO 18076 --- [nio-8080-exec-7] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:9 次
2018-08-16 18:41:10.178 INFO 18076 --- [nio-8080-exec-9] com.souyunku.example.config.LimitAspect : 限流時間段內訪問第:10 次
2018-08-16 18:41:10.702 ERROR 18076 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: 已經到設置限流次數] with root cause

java.lang.RuntimeException: 已經到設置限流次數
at com.souyunku.example.config.LimitAspect.interceptor(LimitAspect.java:73) ~[classes/:na]
at sun.reflect.GeneratedMethodAccessor35.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_112]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_112]/<code>


分享到:


相關文章: