создать базу данных MongoDB и получить к ней доступ внутри вершины vert.x в Kotlin - PullRequest
0 голосов
/ 17 июня 2020

Я хотел бы создать MongoDB и получить к нему доступ через vert.x. Я следую этому учебнику , в котором показано, как подключиться и работать с MongoDB из vert.x, но когда я пытаюсь использовать простой код ниже, он выдает ошибку.

import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.ext.mongo.MongoClient

fun main() {
    val vertx = Vertx.vertx()
    val config = mapOf(Pair("db_name", "testDB"), Pair("connection_string", "mongodb://localhost:27017"))
    val mongoClient = MongoClient.create(vertx, JsonObject(config))
    val document = JsonObject().put("title", "The Hobbit")
    mongoClient.save("books", document) { res ->
        if (res.succeeded()) {
        val id: String = res.result()
        println("Saved book with id $id")
        } else {
        res.cause().printStackTrace()
        }
    }
}

приведенный выше код выдает ошибку ниже

Jun 17, 2020 2:18:48 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Jun 17, 2020 2:18:48 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by com.mongodb.async.client.ClientSessionHelper$1@3315d2d7 from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out

Это моя оценка kotlin Зависимости файлов DSL

dependencies {
    val vertxVersion = "3.9.0"
    implementation(kotlin("stdlib-jdk8"))
    implementation("io.vertx:vertx-lang-kotlin:$vertxVersion")
    implementation("io.vertx:vertx-mongo-client:3.9.0")
}

Я проверил, что MongoDB работает на моем компьютере

enter image description here

Кроме того, как мне создать новую БД, используя vert.x MongoClient API?

1 Ответ

0 голосов
/ 17 июня 2020

Приведенный выше код работает, когда я обращаюсь к mongoClient внутри развернутой вертикали. Вот мой обновленный рабочий код.

import io.vertx.core.AbstractVerticle
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.ext.mongo.MongoClient

internal class BaseVerticle : AbstractVerticle() {
    override fun start() {
        val config = mapOf(Pair("db_name", "mnSet"), Pair("connection_string", "mongodb://localhost:27017"))
        val mongoClient: MongoClient = MongoClient.create(vertx, JsonObject(config))
        val document: JsonObject = JsonObject().put("title", "The Hobbit")
        println("BasicVerticle started")
        mongoClient.save("books", document) { res ->
            if (res.succeeded()) {
                val id: String = res.result()
                println("Saved book with id $id")
            } else {
                res.cause().printStackTrace()
            }
        }
    }
    override fun stop() {
        println("BasicVerticle stopped")
    }
}

fun main() {
    val vertx = Vertx.vertx()
    vertx.deployVerticle(BaseVerticle())
}
...