mongo-java-server icon indicating copy to clipboard operation
mongo-java-server copied to clipboard

Better support for creating MongoClient with new Java API

Open marquiswang opened this issue 2 years ago • 1 comments

The current Mongo Java API gets rid of the MongoClient class, replacing it with an interface. Calls to new MongoClient should be replaced with MongoClients.create. (See https://www.mongodb.com/docs/drivers/java/sync/current/legacy/)

With the old API, we could create a server and then create a client using it with:

MongoServer server = new MongoServer(new MemoryBackend());
InetSocketAddress address = server.bind();
MongoClient client = new MongoClient(address);

This was very convenient, and is what is in the docs.

This is no longer possible with the new MongoClients.create, which takes a ConnectionString, or a String. We're forced to manually create a ConnectionString with:

MongoClient client = MongoClients.create(new ConnectionString(String.format("mongodb://%s:%d", address.getHostString(), addreess.getPort())));

This is repetitive and error-prone. (I kept on using getHostName instead of getHostString, or typoing the connection string format.

It would be really nice to add MongoServer#bindAndGetConnectionString(), or a static method that converts the InetSocketAddress or ServerAddress to a connection string.

marquiswang avatar Jul 25 '22 21:07 marquiswang

Thanks, this change was actually overdue. I’ve introduced bindAndGetConnectionString() as suggested via 342126e1e519026d24559f863c55937bcbd9161f.

I would appreciate if you review the new API and give some feedback.

bwaldvogel avatar Aug 31 '22 13:08 bwaldvogel

The change is available in version 1.42.0.

bwaldvogel avatar Nov 15 '22 12:11 bwaldvogel

I apologize for missing your review request earlier.

Just had a look and I'm pretty happy with the API. Thanks for the fix!

marquiswang avatar Nov 15 '22 20:11 marquiswang