mszmurlo
mszmurlo

Reputation: 1339

Vertx to mongoDB connections

I'm working on a Java/vertx project where the backend is MongoDB (I used to work with Elixir/Erlang since some time, and I'm quite new to vertx but I believe it's the best fit). Basically, I have an http API handled by some HttpServerVerticles which need to store data to (or retrieve data from) the mongo db and to send the appropriate reply to the API caller. I'm looking for the right pattern to implement the queries and the handling of the replies.

From the official guide and some tutorials, I see that for a relational JDBC database, it is necessary to define a dedicated verticle that will handle queries asynchronously. This was my first try with the mongo client but it introduces a lot of boilerplate.

On the other hand, from the mongo client documentation I read that it's Completely non-blocking and that it has its own connection pool. Does that mean that we can safely (from vertx event loop point of view), define and use the mongo client directly in the http verticle ?

Is there any alternative pattern ?

Versions : vertx:3.5.4 / mongodb:4.0.3

Upvotes: 0

Views: 1974

Answers (2)

jvwilge
jvwilge

Reputation: 2534

At our client we use mongodb-driver-rx. Vertx has support for RX (vertx-rx-java) and it fits pretty well on mongodb-driver-rx.

For more information see: https://mongodb.github.io/mongo-java-driver-rx/ https://vertx.io/docs/vertx-rx/java/ https://github.com/vert-x3/vertx-examples/blob/master/rxjava-2-examples/src/main/java/io/vertx/example/reactivex/database/mongo/Client.java

Upvotes: 1

injecteer
injecteer

Reputation: 20699

It's like that: mongo connection pool is exactly like SQL-db pool synchronous and blocking in it's nature, but is wrapped with non-blocking vert.x API around.

So, instead of a normal blocking way of

JsonObject obj = mongo.get( someQuery )

you have rather a non-blocking call out of the box:

mongo.findOne( 'collectionName', someQuery ){ AsyncResult<JsonObject> res ->
  JsonObject obj = res.result()
  doStuff( obj )
}

That means, that you can safely use it directly on the event-loop in any type of verticle without reinventing the asyncronous wheel over and over again.

Upvotes: 1

Related Questions