1. 程式人生 > >Java併發:分散式應用限流實踐

Java併發:分散式應用限流實踐

任何限流都不是漫無目的的,也不是一個開關就可以解決的問題,常用的限流演算法有:令牌桶,漏桶。在之前的文章中,也講到過,但是那是基於單機場景來寫。
然而再牛逼的機器,再優化的設計,對於特殊場景我們也是要特殊處理的。就拿秒殺來說,可能會有百萬級別的使用者進行搶購,而商品數量遠遠小於使用者數量。如果這些請求都進入佇列或者查詢快取,對於最終結果沒有任何意義,徒增後臺華麗的資料。對此,為了減少資源浪費,減輕後端壓力,我們還需要對秒殺進行限流,只需保障部分使用者服務正常即可。

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

歡迎大家加入粉絲群:963944895,群內免費分享Spring框架、Mybatis框架SpringBoot框架、SpringMVC框架、SpringCloud微服務、Dubbo框架、Redis快取、RabbitMq訊息、JVM調優、Tomcat容器、MySQL資料庫教學視訊及架構學習思維導圖

分散式限流

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

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

Redis + Lua 限流示例

本次專案使用 SpringBoot2.0.4,使用到 Redis 叢集, Lua 限流指令碼

引入依賴

<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>

Redis 配置

application.properties

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

Lua 指令碼

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

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

限流注解

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

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();
}

公共配置

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, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {        
RedisTemplate<String, Serializable>
 template = new RedisTemplate<String, Serializable>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);        
return template;    
}
}

攔截器

通過攔截器 攔截 @RateLimit註解的方法,使用 Redsiexecute 方法執行我們的限流指令碼,判斷是否超過限流次數

以下下是核心程式碼

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, Serializable> 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) equestContextHolder.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() > 5) { // "***.***.***.***".length()                
// = 15                
if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));                
}            
}       
} catch (Exception e) {
            ipAddress = "";        
}        
return ipAddress;    
}
}

控制層

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

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

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, ount = 10)    
@GetMapping("/test")    
public String luaLimiter() {        
RedisAtomicInteger entityIdCounter = new RedisAtomicInteger("entityIdCounter", redisTemplate.getConnectionFactory());
        
String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd H:mm:ss.SSS");
        
return date + " 累計訪問次數:" + entityIdCounter.getAndIncrement();    
}
}

啟動服務

package com.souyunku.example;
@SpringBootApplicationpublic class SpringBootLimitApplication {    
public static void main(String[] args) {        
SpringApplication.run(SpringBootLimitApplication.class, args);   
}
}

啟動專案頁面訪問:http://127.0.0.1:8080/test

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

.後臺日誌

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.onfig.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 ontext 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(DelegatingMethodAccessorIpl.java:43) ~[na:1.8.0_112]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_112]