๊ฐœ๋ฐœ/Kotlin

[Ktor] 1. ํด๋ผ์ด์–ธํŠธ, Engine

๋„๋ฆฌ ๐ŸŸ 2021. 8. 4. 16:22

Ktor Client ๊ฐ€์ด๋“œ ์š”์•ฝ ์ •๋ฆฌ



Engine

Ktor HTTP ํด๋ผ์ด์–ธํŠธ๋Š” JVM, Android, JS, Native(iOS/desktop)๊ณผ ๊ฐ™์ด ๋‹ค๋ฅธ ํ”Œ๋žซํผ์—์„œ ์‚ฌ์šฉ๋  ์ˆ˜ ์žˆ๋‹ค. ํŠน์ • ํ”Œ๋žซํผ์—์„œ ๋„คํŠธ์›Œํฌ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ํŠน์ • engine์ด ํ•„์š”ํ•  ์ˆ˜๋„ ์žˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, Android์—์„œ๋Š” OkHttp๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  JVM์—์„œ๋Š” Apache๋‚˜ CIO๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

ktor-client-core ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์™ธ์— ๊ฐ ํ”Œ๋žซํผ์—์„œ ์‚ฌ์šฉํ•  engine์— ๋Œ€ํ•œ ๋””ํŽœ๋˜์‹œ๋Š” ๋ณ„๋„๋กœ ์ถ”๊ฐ€ํ•ด์ค˜์•ผ ํ•œ๋‹ค. Engine dependency ๊ฐ€์ด๋“œ์—์„œ ํ”Œ๋žซํผ ๋ณ„ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ engine๊ณผ ๋””ํŽœ๋˜์‹œ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

ํด๋ผ์ด์–ธํŠธ ์ƒ์„ฑ

HttpClient ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ํด๋ผ์ด์–ธํŠธ๋ฅผ ๋งŒ๋“ ๋‹ค.

engine์„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋„˜๊ธฐ๋Š” ๋ฐฉ์‹

  • ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
  • val client = HttpClient(CIO)
  • [์ฐธ๊ณ ] HttpClient ์ƒ์„ฑ์ž
  • fun HttpClient(engine: HttpClientEngine, block: HttpClientConfig<*>.() -> Unit): HttpClient

engine ์ƒ๋žต ๋ฐฉ์‹

engine์„ ์ƒ๋žตํ•œ ๊ฒฝ์šฐ, Default engine์ด ์ž๋™ ์„ ํƒ๋œ๋‹ค.

  • ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
  • val client = HttpClient(CIO)
  • [์ฐธ๊ณ ] HttpClient ์ƒ์„ฑ์ž
  • fun HttpClient(block: HttpClientConfig<*>.() -> Unit = {}): HttpClient

ํด๋ผ์ด์–ธํŠธ Configuration

์ƒ์„ฑ์ž์— ์ถ”๊ฐ€ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ „๋‹ฌํ•˜์—ฌ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. HttpClientEngineConfig ํด๋ž˜์Šค๊ฐ€ ํด๋ผ์ด์–ธํŠธ ์†์„ฑ ์„ค์ •์˜ ๋ฒ ์ด์Šค ํด๋ž˜์Šค์ด๊ณ , HttpClientConfig ํด๋ž˜์Šค์—์„œ ํ™•์žฅํ•˜์—ฌ ๋” ๋งŽ์€ ์†์„ฑ ์„ค์ •์„ ์ œ๊ณตํ•˜๊ณ  ์žˆ๋‹ค.

val client = HttpClient(CIO) {
      // ์ด block์„ ํด๋ผ์ด์–ธํŠธ configuration block์ด๋ผ๊ณ  ํ•œ๋‹ค.

    expectSuccess = false 
    // expectSuccess: status code๊ฐ€ ์„ฑ๊ณต์ด ์•„๋‹ˆ๋ฉด(code >= 300), HttpClient.receivePipeline ์ข…๋ฃŒ ์˜ต์…˜
}

engine์˜ ์†์„ฑ์€ engine ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ์„ค์ •ํ•œ๋‹ค.

val client = HttpClient(CIO) {
    engine {
        // Configure an engine
    }
}

Plugins

Logging, Authorization Serialization ๋“ฑ๊ณผ ๊ฐ™์€ ์ถ”๊ฐ€ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค.
ํด๋ผ์ด์–ธํŠธ configuration block ์•ˆ์—์„œ install ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ํ”Œ๋Ÿฌ๊ทธ์ธ์„ ๊ฐ€์ ธ์˜จ๋‹ค.

  • ์˜ˆ์‹œ - ๋กœ๊น… ๊ธฐ๋Šฅ ์ถ”๊ฐ€ (Logging plugin)
val client = HttpClient(CIO) {
    install(Logging)
}