標籤:host   ntop   資料庫   conf   parse   scoket   ati   下載   資料   
MongoDB 提供了Java語言操作的驅動jar,我使用的版本是:mongo-java-driver-3.2.2.jar
驅動jar:https://mongodb.github.io/mongo-java-driver/
以下是建立Mongo串連,擷取資料庫和表的方法,拿到表以後可以進行增刪改查的操作,後續章節會更新。
 1  /** 2      * 初始化串連池,設定參數。 3      */ 4     private static void init() { 5  6         // 參數依次是:連結池數量 最大等待時間 scoket逾時時間 設定串連池最長生命時間 連線逾時時間 7         MongoClientOptions options = MongoClientOptions.builder() 8                 .connectionsPerHost(Integer.parseInt(ConfigUtil.getParameter("mongodb.connectionsPerHost"))) 9                 .maxWaitTime(Integer.parseInt(ConfigUtil.getParameter("mongodb.maxWaitTime")))10                 .socketTimeout(Integer.parseInt(ConfigUtil.getParameter("mongodb.socketTimeout")))11                 .maxConnectionLifeTime(Integer.parseInt(ConfigUtil.getParameter("mongodb.maxConnectionLifeTime")))12                 .connectTimeout(Integer.parseInt(ConfigUtil.getParameter("mongodb.connectTimeout"))).build();13 14         // 串連到MongoDB服務 如果是遠端連線可以替換“localhost”為伺服器所在IP地址15         // ServerAddress()兩個參數分別為 伺服器位址 和 連接埠16         ServerAddress serverAddress = new ServerAddress(ConfigUtil.getParameter("mongodb.hostName"),17                 Integer.parseInt(ConfigUtil.getParameter("mongodb.port")));18         List<ServerAddress> addrs = new ArrayList<ServerAddress>();19         addrs.add(serverAddress);20 21         // 三個參數分別為 使用者名稱 資料庫名稱 密碼22         MongoCredential credential = MongoCredential.createScramSha1Credential(23                 ConfigUtil.getParameter("mongodb.username"), ConfigUtil.getParameter("mongodb.databaseName"),24                 ConfigUtil.getParameter("mongodb.password").toCharArray());25         List<MongoCredential> credentials = new ArrayList<MongoCredential>();26         credentials.add(credential);27 28         // 通過串連認證擷取MongoDB串連29         client = new MongoClient(addrs, credentials, options);30     }
 1 /** 2      * 根據名稱擷取DB,相當於是串連 3      *  4      * @param dbName 5      * @return 6      */ 7     public static MongoDatabase getDatabase() { 8         if (client == null) { 9             // 初始化10             init();11         }12         return client.getDatabase(ConfigUtil.getParameter("mongodb.databaseName"));13     }14     /**15      * 擷取Collection16      * @param collectionName17      * @return18      */19     public static MongoCollection<Document> getCollection(String collName){20         if (client == null) {21             // 初始化22             init();23         }24         MongoDatabase db = getDatabase();25         MongoCollection<Document> collection = db.getCollection(collName);  26         return collection;27     }
 
java操作mongodb——串連資料庫