iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 24
0
Modern Web

最好用的非同步網頁框架!開始用 Ktor 寫 Kotlin Server系列 第 24

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

  • 分享至 

  • twitterImage
  •  

今天我們來談談 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)
}

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


上一篇
[Day 23] 用 POST 存取第三方 API
下一篇
[Day 25] parallel request ,談 coroutine
系列文
最好用的非同步網頁框架!開始用 Ktor 寫 Kotlin Server30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言