Kotlin,  Ktor

Kotlin > Ktor > Auto Reloadを有効にする

Table of Content

以下のような感じで、ソースの変更でAuto Reloadがかかるようにします。

設定ファイル

application.confに以下を追加します。

  • development: trueにする
  • watch: 監視対象。
    今回の場合には /build/classesが監視対象となる。
ktor {
    deployment {
        port = 8080
        port = ${?PORT}
        watch = [ classes ]
    }
    application {
        modules = [ com.example.ApplicationKt.module ]
    }
    development = true
}

watchは他にも以下のように設定できる模様

watch = [ / ]
watch = [ classes, resources ]

Auto-reload | Ktor

監視タスクの起動

terminalで以下を実行し、ソースが変更されたら再ビルドがかかるようにします。

gradle -t installDist

  or (↑どちらかお好きな方で↓)

gradlew -t build

タスクが起動します。

gradle -t installDist

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/7.0/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 765ms
6 actionable tasks: 6 up-to-date

Waiting for changes to input files of tasks... (ctrl-d to exit)
<-------------> 0% WAITING
> IDLE

実行

通常通り実行する。

以下のようにWatchingと表示されていればOK

2021-08-12 12:46:38.361 [main] DEBUG Application - Java Home: /Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents
2021-08-12 12:46:38.362 [main] DEBUG Application - Class Loader: jdk.internal.loader.ClassLoaders$AppClassLoader
2021-08-12 12:46:38.370 [main] DEBUG Application - Watching /Users/atsu/Downloads/ktor-autoreload/build/classes/kotlin/main/com/example for changes.
2021-08-12 12:46:38.370 [main] DEBUG Application - Watching /Users/atsu/Downloads/ktor-autoreload/build/classes/kotlin/main for changes.
2021-08-12 12:46:38.370 [main] DEBUG Application - Watching /Users/atsu/Downloads/ktor-autoreload/build/classes/kotlin/main/META-INF for changes.
2021-08-12 12:46:38.370 [main] DEBUG Application - Watching /Users/atsu/Downloads/ktor-autoreload/build/classes/kotlin/main/com for changes.
2021-08-12 12:46:38.775 [main] INFO  Application - Responding at http://0.0.0.0:8080

変更

ソースを変更したら、gradle -t installDist が変更を検知して再ビルドがかかります

modified: /Users/atsu/Downloads/ktor-autoreload/src/Application.kt
Change detected, executing build...

> Task :compileKotlin
w: /Users/atsu/Downloads/ktor-autoreload/src/Application.kt: (12, 24): Parameter 'testing' is never used

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/7.0/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 850ms
6 actionable tasks: 5 executed, 1 up-to-date

Waiting for changes to input files of tasks... (ctrl-d to exit)
<<=============> 100% EXECUTING [1m 28s]
> IDLE

その他

GraphQLのデバッグにも重宝できそうです

参考

Auto-reload | Ktor

https://www.youtube.com/watch?v=Axwqfab_OUk

https://www.youtube.com/watch?v=y-8K3xzuoak