For the MongoDB Java driver, after 2.10.0, the document reminds that the Mongo class will be abolished and the mongoclient class is encouraged at the beginning.
The following shows how a Java program uses the latest mongoclient class to write data to MongoDB.
Assume that there is already a replica-Set cluster, namely, D1, D2, and D3 virtual machines.
Create a Java application built by Maven. Maven exec plugin is used to conveniently execute jar packages and customize parameters.
Let's take a look at pom. xml:
<build> <plugins> <plugin><groupId>org.codehaus.mojo</groupId><artifactId>exec-maven-plugin</artifactId><version>1.2.1</version><executions> <execution> <goals> <goal>java</goal> </goals> </execution></executions><configuration> <mainClass>org.freebird.dbtool.App</mainClass> <arguments> <argument>d1,d2,d3</argument> </arguments></configuration> </plugin> </plugins> </build>
Three parameters are passed. They are separated by commas (,). They are different host names: D1, D2, and D3.
Check out the code initialization section:
public static void main(String[] args) throws UnknownHostException {System.out.println(args[0]); String[] hosts = args[0].split(","); int portNumber = 27017; System.out.println(hosts[0]); System.out.println(hosts[1]); System.out.println(hosts[2]); MongoClient client = new MongoClient(Arrays.asList(new ServerAddress(hosts[0], portNumber), new ServerAddress(hosts[1], portNumber), new ServerAddress(hosts[2], portNumber))); MyApp.getInstance().setDbName("kaimei"); MyApp.getInstance().setClient(client);
The three hosts are separated, and three serveraddress objects are created, and then the Consumer Client object is constructed.
At the same time, a singleton object of MyApp is created to store this Consumer Client object, and getdb () is provided to facilitate database connection obtaining in the future.
public class MyApp { private MyApp() { } public static MyApp getInstance() { return MyAppHolder.INSTANCE; } private static class MyAppHolder { private static final MyApp INSTANCE = new MyApp(); } @Getter @Setter String dbName; @Setter MongoClient client; public DB getDB() { return client.getDB(dbName); }}
When you need to use a connection anywhere in the future:
public static void bind(final String address, final String userId) {DB db = MyApp.getInstance().getDB();DBCollection collection = db.getCollection(DISPLAY_COLLECTION);DBObject condition = new BasicDBObject();condition.put("address", address);DBObject field = new BasicDBObject();field.put("user_id", new ObjectId(userId));DBObject set = new BasicDBObject();set.put("$set", field);collection.update(condition, set, false, false); }
It's easy.