mongo-java-server
mongo-java-server copied to clipboard
Better support for creating MongoClient with new Java API
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.
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.
The change is available in version 1.42.0
.
I apologize for missing your review request earlier.
Just had a look and I'm pretty happy with the API. Thanks for the fix!