package com.fahai;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
public enum MongoDBUtil {
/**
* 定义一个枚举的元素,它代表此类的一个实例
*/
instance;
private MongoClient mongoClient;
static{
System.out.println("=========MongoDBUtil初始化===============");
CompositeConfiguration config = new CompositeConfiguration();
try {
config.addConfiguration(new PropertiesConfiguration("mongodb.properties"));
} catch (ConfigurationException e) {
e.printStackTrace();
}
//从配置文件中获取属性值
String ip = config.getString("host");
int port = config.getInt("port");
instance.mongoClient = new MongoClient(ip,port);
//or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
//List
listHost = Arrays.asList(new ServerAddress("localhost",27017),new ServerAddress("localhost",27018));
//instance.mongoClient = new MongoClient(listHost);
//大部分用户使用mongodb都在安全网下,但是如果将mongodb设为安全模式,就需要在客户端提供用户名和密码
//boolean auth = db.authenticate(myUserName,myPassword);
Builder options = new MongoClientOptions.Builder();
options.connectionsPerHost(300);//连接池设置为300个连接,默认为10
options.connectTimeout(15000);//连接超时,推荐>3000毫秒
options.maxWaitTime(5000);
options.socketTimeout(0);//套接字超时时间,0无限制
options.threadsAllowedToBlockForConnectionMultiplier(5000);//线程队列数,如果连接线程排满队列就会抛出Out of semaphores to get db错误
options.writeConcern(WriteConcern.SAFE);
options.build();
}
//-------------------公用方法---------------------------
/**
* 获得db实例
*/
public MongoDatabase getDB(String dbName){
if (dbName != null && !"".equals(dbName)) {
MongoDatabase database = mongoClient.getDatabase(dbName);
return database;
}
return null;
}
/**
* 获取collection对象
*/
public MongoCollection getCollection(String dbName,String collName){
if(null == collName || "".equals(collName)){
return null;
}
if (null == dbName || "".equals(dbName)) {
return null;
}
MongoCollection collection = mongoClient.getDatabase(dbName).getCollection(collName);
return collection;
}
/**
* 查询db下的所有表名
*/
public List getAllCollections(String dbName){
MongoIterable colls = getDB(dbName).listCollectionNames();
ArrayList _list = new ArrayList();
for (String s : colls) {
_list.add(s);
}
return _list;
}
/**
* 获取所有数据库名列表
*/
public MongoIterable getAllDBName(){
MongoIterable s = mongoClient.listDatabaseNames();
return s;
}
/**
* 删除一个数据库
*/
public void dropDB(String dbName){
getDB(dbName).drop();
}
/**
* 查找对象 - 根据主键_id
*/
public Document findById(MongoCollection coll,String id){
ObjectId _idobj = new ObjectId(id);
Document myDoc = coll.find(Filters.eq("_id",_idobj)).first();
return myDoc;
}
/**
* 统计数
*/
public int getCount(MongoCollection coll){
int count = (int) coll.count();
return count;
}
/**
* 条件查询
*/
public MongoCursor find(MongoCollection coll,Bson filter){
return coll.find(filter).iterator();
}
/**
* 分页查询
*/
public MongoCursor findByPage(MongoCollection coll,Bson filter,int pageNo,int pageSize){
Bson ordetBy = new BasicDBObject("_id",1);
return coll.find(filter).sort(ordetBy).skip((pageNo-1)*pageSize).limit(pageSize).iterator();
}
/**
* 通过id删除
*/
public int deleteById(MongoCollection coll,String id){
int count = 0;
ObjectId _id = new ObjectId(id);
Bson filter = Filters.eq("_id",_id);
DeleteResult deleteOne = coll.deleteOne(filter);
count = (int) deleteOne.getDeletedCount();
return count;
}
/**
* FIXME
*/
public Document updateById(MongoCollection coll,String id,Document newdoc){
ObjectId _idobj = new ObjectId(id);
Bson filter = Filters.eq("_id",_idobj);
coll.updateOne(filter, new Document("$set",newdoc));
return newdoc;
}
public void dropCollection(String dbName,String collName){
getDB(dbName).getCollection(collName).drop();
}
/**
* 关闭mongodb
*/
public void close(){
if (mongoClient != null) {
mongoClient.close();
mongoClient = null;
}
}
/**
* 测试
*/
public static void main(String[] args) {
String dbName = "GC_MAP_DISPLAY_DB";
String collName = "COMMUNITY_BJ";
MongoCollection coll = MongoDBUtil.instance.getCollection(dbName, collName);
//
插入多条
// for (int i = 1; i <= 4; i++) {
// Document doc = new Document();
// doc.put("name", "zhoulf");
// doc.put("school", "NEFU" + i);
// Document interests = new Document();
// interests.put("game", "game" + i);
// interests.put("ball", "ball" + i);
// doc.put("interests", interests);
// coll.insertOne(doc);
// }
//查询当前mongodb中所有库的名称
/*MongoIterable allDBName = MongoDBUtil.instance.getAllDBName();
for (String string : allDBName) {
System.out.println(string);
}*/
//查询某个库中多有表的名称
/*List allCollections = MongoDBUtil.instance.getAllCollections("mydb");
for (String string : allCollections) {
System.out.println(string);
}*/
// // 根据ID查询
// String id = "58d78fff23d7a926c8165957";
// Document doc = MongoDBUtil.instance.findById(coll, id);
// System.out.println(doc);
// 查询多个
MongoCursor cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();
while (cursor1.hasNext()) {
org.bson.Document _doc = (Document) cursor1.next();
System.out.println(_doc.toString());
}
cursor1.close();
// 查询多个
// MongoCursor cursor2 = coll.find(Person.class).iterator();
// 删除数据库
// MongoDBUtil2.instance.dropDB("testdb");
// 删除表
// MongoDBUtil2.instance.dropCollection(dbName, collName);
// 修改数据
// String id = "556949504711371c60601b5a";
// Document newdoc = new Document();
// newdoc.put("name", "时候");
// MongoDBUtil.instance.updateById(coll, id, newdoc);
// 统计表
// System.out.println(MongoDBUtil.instance.getCount(coll));
// 查询所有
// Bson filter = Filters.eq("count", 0);
// MongoDBUtil.instance.find(coll, filter);
}
}