[英]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.