[英]Vertx list of Rest API call in loop
我是 vertx 和 Java 環境的新手。 下面的代碼調用 rest API 端點列表並將結果存儲在 MongoDB 中,它可以工作,但我不確定這是在 vertx 環境中執行此操作的正確方法。 另外,有什么需要改進的地方嗎?
val deviceRepository = listOf("10.2.0.106",
"10.2.0.120",
"10.2.0.115",
"10.2.0.112",
"10.2.0.118",
"10.2.0.119")
internal class DeviceListVerticle : AbstractVerticle() {
@OptIn(UnstableDefault::class)
@ImplicitReflectionSerializer
override fun start() {
// mongo client connection
val config = mapOf(Pair("db_name", "deviceList"), Pair("connection_string", "mongodb://localhost:27017"))
val mongoClient: MongoClient = MongoClient.create(vertx, JsonObject(config))
val httpClient = WebClient.create(vertx)
// loop through each IP address in deviceRepository and call rest end point http://{IP}/information/device
deviceRepository.forEach { deviceIP ->
val request: HttpRequest<Buffer> = httpClient.get(deviceIP, "information/device")
request.send { ar ->
if (ar.succeeded()) {
// Obtain response
val response = ar.result()
mongoClient.save("devices", response.bodyAsJsonObject()) { res ->
if (res.succeeded()) {
val id: String = res.result()
println("Saved device with id $id")
} else {
res.cause().printStackTrace()
}
}
} else {
println("Something went wrong " + ar.cause().message)
}
}
}
}
override fun stop() {
println("DeviceListVerticle stopped")
}
}
fun main() {
val vertx = Vertx.vertx()
vertx.deployVerticle(DeviceListVerticle())
}
對於一次性任務,我認為使用沒有Verticle
的WebClient
會更好。 我認為 Verticle 非常適合將響應式計算(例如,服務請求、定期執行)封裝到並發和部署友好的包中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.