package com.voice.mongodb;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import
com.mongodb.Mongo;
import com.mongodb.MongoException;
import
com.mongodb.WriteConcern;
public class MongoDB {
private Mongo wMongodb;
private static MongoDB instance =
null;
private static synchronized MongoDB
GetInstance()
{
if(instance == null)
{
instance = new
MongoDB();
}
return instance;
}
private MongoDB()
{
try {
// wMongodb = new
Mongo("172.16.10.15", 27020);
wMongodb = new Mongo("wmongo.olavoice.com",
27020);
wMongodb.getMongoOptions().autoConnectRetry = true;
DB db =
wMongodb.getDB("olacloud");
// DB db =
wMongodb.getDB("olacloud_internal");
db.authenticate("olacloud",
"olacloud".toCharArray());
db.setWriteConcern(WriteConcern.SAFE);
}
catch (UnknownHostException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
} catch (MongoException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取数据库连接
* @return 已经连接的数据库
*/
public static DB getDB()
{
DB db = MongoDB.GetInstance().wMongodb.getDB("olacloud");
// DB db =
MongoDB.GetInstance().wMongodb.getDB("olacloud_internal");
return
db;
}
/**
* 获取table的连接
* @param tableName table名
* @return
table连接
*/
public static DBCollection getDBCollection(String tableName)
{
DB db = MongoDB.getDB();
DBCollection col =
db.getCollection(tableName);
return col;
}
/**
*
关闭当前的Mongodb连接
*/
public static void close() {
if (instance != null)
{
instance.wMongodb.close();
}
}
}
原文:http://www.cnblogs.com/Wen-yu-jing/p/3783430.html