简体   繁体   中英

Mongodb Async vs Sync Java driver

I´m quite confused about java drivers for Mongodb. Reading the official documentation it seems that you can use the normal MondoDB Driver or the MongoDB Async Driver.

The first question is: Can I use both in the same application or I have to choose one?

Trying to use the Async driver I found things that I used to do (with the normal driver) in which I get a bit lost now. For example, I used to do this:

FindIterable<Document> iterable = db.getCollection("my_coll").find(query);
String json = JSON.serialize(iterable);

And now I really don´t know how to convert the result into a json string since they have not included the JSON class from the Async driver. Second question: If I cannot use both drivers at the same time, how can I then serialize a FindIterable<Document> ?

The answers are:

  • Yes of course you can use both drivers. In fact, if you really care about performance in your application you should use the Sync driver for those actions that you need a response from MongoDB (like find()). And you will use the Async driver for the ones that you don't really need it, for "fire and forget" actions (like insert or update).
  • So the serialization question gets answered from the above. If you get a response you are using the sync driver, therefore you can keep using JSON class:

JSON.serialize(iterable);

One thing to be conscious of is that the two drivers share some dependencies. Try to align the versions of the drivers such that they are both expecting the same version of their common dependencies otherwise you can end up with some 'Class not found' type issues resulting from the class loader picking an incompatible version of a class for one or other of the drivers.

I'd add that the use-case I found the async driver great for was a large export style query, where I had to return a large amount of data from a web service. In this case I had to return a large CSV. Previously this method would use up a lot of RAM building up the whole set of CSV data up before writing it to the client. Using the async driver I could read small batches (500 records at a time seemed optimal) from MongoDB and write them to the browser client in a chunked response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM