在系統開發中,我們經常需要保護一些安全性較高的接口,限制這些接口每秒處理的請求數量。例如對於一個計算密集型接口,假設壓測值是100rps, 如果實際情況長期高於這個值,則會引起滾雪球效應,最終導致系統崩潰。下面我們一起來看看如何在 Play 中實現一個完全異步非阻塞的請求限速 ?本文代碼已提交至 play-community 項目,詳情請參考 controllers.demo.ThrottleDemoController 。
1 實現思路
當 Controller 接收到請求時,爲該請求建立一個“開關”,並且把該“開關”發送給“限速器”,"限速器"通過“開關”控制請求的處理速度。本文采用 Promise 實現“開關”,使用 Akka Stream 的 SouceQueue 實現“限速器”。
2 實現代碼
2.1 開關
創建 ThrottledRequest 類,用於存放“開關”和請求到達時間,
case class ThrottledRequest(promise: Promise[Boolean], time: Long)
2.2 限速器
使用 SourceQueue 創建“限速器”,處理請求限速和請求超時,
val sourceQueue = Source .queue[ThrottledRequest](100, OverflowStrategy.backpressure) .throttle(1, 1.second, 1, ThrottleMode.shaping) .toMat(Sink.foreach{ r => // 處理未超時請求 if (System.currentTimeMillis() - r.time <= 15000) { r.promise.success(false) } else { r.promise.success(true) } })(Keep.left).run()
Source.queue 方法的聲明如下,
def queue[T](bufferSize: Int, overflowStrategy: OverflowStrategy): Source[T, SourceQueueWithComplete[T]]
這裏我們設置緩衝區大小爲 100, 設置緩衝區溢出時的處理策略爲 backpressure ,以防止請求丟失。通過 throttle 方法設置請求處理速度爲 1 個每秒。 Sink 負責處理請求的放行和超時。
2.3 請求攔截
請求攔截 Action 負責攔截所有發往目標 Action 的請求,爲每個請求創建“開關”併發送給“限速器”,然後只放行被“限速器”打開開關的請求,
// 只有通過限速器(sourceQueue)的請求才會被執行 def throttle[A](action: Action[A]) = Action.async(action.parser) { request => val promise = Promise[Boolean]() sourceQueue.offer(ThrottledRequest(promise, System.currentTimeMillis())) promise.future.flatMap{ isTimeout => if (!isTimeout) { action(request) } else { Future.successful(Forbidden("Timeout.")) } } }
2.4 目標 Action
目標 Action 組合了攔截 Action,代碼如下,
def throttledAction = throttle { Action { implicit request: Request[AnyContent] => Ok("Finish.") }}
2.5 定義路由
GET /demo/throttle controllers.demo.ThrottleDemoController.throttledAction
3 測試實現
上面我們實現了一個限速接口,每秒只處理 1 個請求,當請求排隊超過 15 秒時, 直接返回 403 響應。 我們通過下面的測試代碼, 將 100 個請求瞬間發送過去,然後異步打印響應信息,
val client = buildAHCClient (1 to 100).foreach{ _ => client.prepareGet(s"http://localhost:9000/demo/throttle") .execute(new AsyncCompletionHandler[Response] { override def onCompleted(response: Response): Response = { println(s"status: ${response.getStatusCode}, time: ${DateTime.now().toString("HH:mm:ss")}") response } }) } Thread.sleep(100000) client.close()
測試結果如下:
status: 200, time: 23:22:06 status: 200, time: 23:22:07 status: 200, time: 23:22:08 status: 200, time: 23:22:09 status: 200, time: 23:22:10 status: 200, time: 23:22:11 status: 200, time: 23:22:12 status: 200, time: 23:22:13 status: 200, time: 23:22:14 status: 200, time: 23:22:15 status: 200, time: 23:22:16 status: 200, time: 23:22:17 status: 200, time: 23:22:18 status: 200, time: 23:22:19 status: 200, time: 23:22:20 status: 200, time: 23:22:21 status: 403, time: 23:22:22 status: 403, time: 23:22:23 ...
從上面可以看出,請求按照到達順序依次被處理,從響應時間上看,目標接口確實每秒只處理 1 個請求, 並且從 23時22分22秒 開始,後面的請求均被超時處理。
4 小結
異步非阻塞代碼雖然寫起來有點麻煩,並且不易於調試,但是在系統性能方面收益是巨大的。在相同的系統性能指標下,異步非阻塞代碼可以讓硬件成本降到最低。理論上,使用異步非阻塞方式編寫的系統可以在單個線程上運行,並且可以保證較高的併發性,典型例子是Node.js。Play Framework 是一個完全異步非阻塞的 Web 開發框架,相信在不久的將來在國內會越來越受歡迎。