標籤:
1 package com.voice.db; 2 3 import com.mongodb.DB; 4 import com.mongodb.DBCollection; 5 import com.mongodb.Mongo; 6 import com.mongodb.MongoClient; 7 import com.mongodb.MongoClientOptions; 8 import com.mongodb.ReadPreference; 9 import com.mongodb.ServerAddress; 10 import com.mongodb.WriteConcern; 11 12 13 public class MongoDB { 14 15 private Mongo wMongodb; 16 17 private static MongoDB instance = null; 18 19 private static synchronized MongoDB GetInstance() 20 { 21 if(!isInstanceAlive()) 22 { 23 instance = new MongoDB(); 24 } 25 return instance; 26 } 27 28 /** 29 * 判斷資料庫是否處於串連狀態中 30 * @return true:串連中<br/> 31 * false:已斷開 32 */ 33 private static boolean isInstanceAlive() { 34 boolean retBool = false; 35 try { 36 // 嘗試訪問一次資料庫 37 DBCollection col = instance.wMongodb.getDB("database_name").getCollection("table_name"); 38 col.count(); 39 retBool = true; 40 } catch (Exception e) { 41 try { 42 instance.wMongodb.close(); 43 } catch (Exception ex) {} 44 } 45 return retBool; 46 } 47 48 private MongoDB() 49 { 50 try { 51 MongoClientOptions.Builder voicedbBuilder = MongoClientOptions.builder(); 52 voicedbBuilder.connectTimeout(3000); 53 voicedbBuilder.socketTimeout(6000); 54 voicedbBuilder.autoConnectRetry(true); 55 voicedbBuilder.connectionsPerHost(5); 56 voicedbBuilder.readPreference(ReadPreference.secondaryPreferred()); 57 voicedbBuilder.socketKeepAlive(true); 58 MongoClientOptions voicedbOptions = voicedbBuilder.build(); 59 60 // wMongodb = new MongoClient(new ServerAddress("172.16.10.15", 27020),voicedbOptions); 61 wMongodb = new MongoClient(new ServerAddress("localhost", 27020),voicedbOptions); 62 63 DB db = wMongodb.getDB("db_name"); 64 // DB db = wMongodb.getDB("olacloud_internal"); 65 db.authenticate("id", "id".toCharArray()); 66 db.setWriteConcern(WriteConcern.SAFE); 67 } catch (Exception e) { 68 // TODO Auto-generated catch block 69 e.printStackTrace(); 70 } 71 72 } 73 74 /** 75 * 擷取資料庫連接 76 * @return 已經串連的資料庫 77 */ 78 public static DB getDB() { 79 DB db = MongoDB.GetInstance().wMongodb.getDB("db_name"); 80 // DB db = MongoDB.GetInstance().wMongodb.getDB("olacloud_internal"); 81 return db; 82 } 83 84 /** 85 * 擷取table的串連 86 * @param tableName table名 87 * @return table串連 88 */ 89 public static DBCollection getDBCollection(String tableName) { 90 DB db = MongoDB.getDB(); 91 DBCollection col = db.getCollection(tableName); 92 return col; 93 } 94 95 /** 96 * 關閉當前的Mongodb串連 97 */ 98 public static void close() { 99 if (instance != null) {100 instance.wMongodb.close();101 }102 }103 104 }
MongoDB的對象的建立