[Day 24] 如果有很多 Request 怎麼辦,談 Parallel requests

今天我們來談談 Parallel requests

多個 API 連線

我們先開兩個測試的 route:

get("/a") {
    call.respondText("a", contentType = ContentType.Text.Plain)
}

get("/b") {
    call.respondText("b", contentType = ContentType.Text.Plain)
}

get("/c") {
    call.respondText("c", contentType = ContentType.Text.Plain)
}

然後,我們可以存取這三個 API:

get("/") {
    val a = client.get<String>("http://127.0.0.1:8080/a")
    val b = client.get<String>("http://127.0.0.1:8080/b")
    val c = client.get<String>("http://127.0.0.1:8080/c")
    client.close()
    call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
}

Parallel requests

如果我們的 API 耗時比較久的話,那會怎麼樣呢?

我們把之前的 API 調整一下,每個 API 加上 2 秒的延遲:

import kotlinx.coroutines.delay

get("/a") {
    delay(2000)
    call.respondText("a", contentType = ContentType.Text.Plain)
}

get("/b") {
    delay(2000)
    call.respondText("b", contentType = ContentType.Text.Plain)
}

get("/c") {
    delay(2000)
    call.respondText("c", contentType = ContentType.Text.Plain)
}

這樣的話,我們會發現 http://127.0.0.1:8080/ 的時間變比較長了,每個 API 都多花 2 秒,整體大約是 6 秒左右。

如果我們改成平行存取的方式:

get("/") {
    val a = async { client.get<String>("http://127.0.0.1:8080/a") }
    val b = async { client.get<String>("http://127.0.0.1:8080/b") }
    val c = async { client.get<String>("http://127.0.0.1:8080/c") }
    client.close()
    call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
}

這樣,我們的時間就變短了。