对象类MongoClient 操作MongoDB replicaset

每日一贴,今天的内容关键字为对象类

    对于MongoDB的Java动驱, 从2.10.0版本后,文档中提示Mongo类将会被除废,当初开始都励鼓应用MongoClient类。

    上面演示一个Java程序如何应用最新的MongoClient类来对MongoDB写作操。

    首先假设已经有了一个Replica-set群集,分别是d1, d2和 d3三台虚拟机。

    然后建创一个Maven构建的Java应用程序。应用了maven exec plugin用来便利行执jar包和定制参数。

    看一下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>

    传递了三个参数,间中用,离隔,分别是不同的机主名称:d1, d2, d3.

    看看代码初始化分部:

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);
    每日一道理
成功的花朵开放在啊勤劳的枝头,失败的苦果孕育在懒惰的温床之中。

    这里将三个host用,分割开后,建创三个ServerAddress对象,然后构建MongoClient对象。

    同时建创了一个MyApp的singleton对象,寄存这个MongoClient对象,并供给了getDB()便利后日获得数据库连接。

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);
    }
}

    后以在任何地方要需应用连接的时候,这样应用:

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);
    }

    很简单吧。

文章结束给大家分享下程序员的一些笑话语录: 《诺基亚投资手机浏览器UCWEB,资金不详或控股》杯具了,好不容易养大的闺女嫁外国。(心疼是你养的吗?中国创业型公司创业初期哪个从国有银行贷到过钱?)

原文地址:https://www.cnblogs.com/xinyuyuanm/p/3067562.html