每日一貼,今天的內容關鍵字為對象類
????對于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,資金不詳或控股》杯具了,好不容易養大的閨女嫁外國。(心疼是你養的嗎?中國創業型公司創業初期哪個從國有銀行貸到過錢?)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
