一个MongoDB的工具类
package utils.mongodb;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import play.Play;
import utils.Page;
import utils.ParamUtil;
import net.sf.json.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import com.mongodb.util.JSON;
import conf.ResourceConfig;
/**
* @Description: MongoDB工具类,提供基本的对mongoDB的操作方法
* @author Li Weidong
* @date 2016-4-12
*/
public class MongoDBUtil {
private static final String host = ResourceConfig.getValue("mongodb.host");
//用户名
private static final String userName = ResourceConfig.getValue("mongodb.username");
//数据库
public static final String database = ResourceConfig.getValue("mongodb.database");
//密码
private static final String password = ResourceConfig.getValue("mongodb.password");
private static Mongo mongoClient = null;
static {
initDBClient();
}
private static void initDBClient() {
synchronized (MongoDBUtil.class) {
if (null == mongoClient) {
// 用户名 数据库 密码
MongoCredential credential = MongoCredential.createCredential(userName, database, password.toCharArray());
/*mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential),
getConfOptions());*/
mongoClient = new MongoClient(getServerAddressList(), Arrays.asList(credential), getConfOptions());
}
}
}
private static List<ServerAddress> getServerAddressList(){
if(ParamUtil.isString(host)){
List<ServerAddress> list = new ArrayList<ServerAddress>();
if(host.contains(",")){
String[] hostAndPort = host.split(",");
if(hostAndPort!=null && hostAndPort.length>0){
for(int i=0;i<hostAndPort.length;i++){
String s = hostAndPort[i];
if(s.contains(":")){
int ht = s.indexOf(":");
String h = s.substring(0, ht);
Integer p = Integer.valueOf(s.substring(ht+1, s.length()));
ServerAddress serverAddress = new ServerAddress(h, p);
list.add(serverAddress);
}
}
}
}else{
int ht = host.indexOf(":");
String h = host.substring(0, ht);
Integer p = Integer.valueOf(host.substring(ht+1, host.length()));
ServerAddress serverAddress = new ServerAddress(h, p);
list.add(serverAddress);
}
return list;
}
return null;
}
/*private static void initDBClient() {
synchronized (MongoDBUtil.class) {
if (null == mongoClient) {
mongoClient = new MongoClient(new ServerAddress(host, port),
getConfOptions());
}
}
}*/
public boolean delete(String dbName, String collectionName, String[] keys,
Object[] values) {
DB db = null;
DBCollection dbCollection = null;
if (keys != null && values != null) {
// 如果keys和values不对等,直接返回false
if (keys.length != values.length) {
return false;
}
try {
dbCollection = getDBCollection(dbName, collectionName);
BasicDBObject doc = new BasicDBObject();
WriteResult result = null;
for (int i = 0; i < keys.length; i++) {
doc.put(keys[i], values[i]);
}
result = dbCollection.remove(doc);
return (result != null) ? false : true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
public static void deleteById(String dbName, String collectionName,
Object id) {
DBCollection coll = MongoDBUtil.getDBCollection(dbName, collectionName);
DBObject search = coll.findOne(new BasicDBObject("_id", id));
if (null != search) {
WriteResult result = coll.remove(search);
}
}
public static GridFS getGridFS(DB db, String collectionName) {
return new GridFS(db, collectionName);
}
public static void saveFile(final String dbName,
final String collectionName, final File file,
Map<String, String> meta) throws Exception {
try {
DB db = getDB(dbName);
GridFS myFS = getGridFS(db, collectionName);
GridFSFile gff = myFS.createFile(file);
if (null != meta) {
JSONObject jObj = JSONObject.fromObject(meta);
DBObject dbo = (DBObject) JSON.parse(jObj.toString());
gff.setMetaData(dbo);
}
gff.save();
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
public static void saveFile(final String dbName,
final String collectionName, final InputStream is,final String fileName,
Map<String, String> meta) throws Exception {
try {
DB db = getDB(dbName);
GridFS myFS = getGridFS(db, collectionName);
GridFSFile gff = myFS.createFile(is, fileName);
if (null != meta) {
JSONObject jObj = JSONObject.fromObject(meta);
DBObject dbo = (DBObject) JSON.parse(jObj.toString());
gff.setMetaData(dbo);
}
gff.save();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public static byte[] getFileByName(final String dbName,
final String collectionName, final String fileName)
throws Exception {
try {
DB db = getDB(dbName);
GridFS myFS = getGridFS(db, collectionName);
GridFSDBFile file_ = myFS.findOne(fileName);
if (null == file_)
return null;
InputStream is = file_.getInputStream();
long len = file_.getLength();
byte[] bts = new byte[(int) len];
is.read(bts);
return bts;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
public static GridFSDBFile getGridFSDBFileByName(final String dbName,
final String collectionName, final String fileName)
throws Exception {
try {
DB db = getDB(dbName);
GridFS myFS = getGridFS(db, collectionName);
GridFSDBFile file_ = myFS.findOne(fileName);
return file_;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public static void delFileByName(final String dbName,
final String collectionName, final String fileName)
throws Exception {
try {
DB db = getDB(dbName);
GridFS myFS = getGridFS(db, collectionName);
// GridFSDBFile file_=myFS.findOne(fileName);
myFS.remove(fileName);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public static void insert(String dbName, String collectionName, Object obj) {
if (null == obj) {
throw new NullPointerException("the obj is null");
}
DBCollection dbCollection = getDBCollection(dbName, collectionName);
JSONObject jObj = JSONObject.fromObject(obj);
DBObject dbo = (DBObject) JSON.parse(jObj.toString());
WriteResult result = dbCollection.insert(dbo);
System.out.println(result.toString());
}
public static void insert(final String dbName, final String collectionName, DBObject obj) {
if (null == obj) {
throw new NullPointerException("the obj is null");
}
DBCollection dbCollection = getDBCollection(dbName, collectionName);
JSONObject jObj = JSONObject.fromObject(obj);
DBObject dbo = (DBObject) JSON.parse(jObj.toString());
WriteResult result = dbCollection.insert(dbo);
System.out.println(result.toString());
}
public static void batchInsert(String dbName, String collectionName,
List<? extends DBObject> objs) {
if (null == objs) {
throw new NullPointerException("the mongo objs is null");
}
DBCollection dbCollection = getDBCollection(dbName, collectionName);
WriteResult result = dbCollection.insert(objs);
// System.out.println(result.getN());
// System.out.println(result.getUpsertedId());
// System.out.println("--------------");
System.out.println(result.toString());
}
public static void updateByDBObject(String dbName, String collectionName,
DBObject updateObj, Object id) {
DBCollection dbCollection = getDBCollection(dbName, collectionName);
DBObject search = dbCollection.findOne(new BasicDBObject("_id", id));
if (null == search)
throw new NullPointerException("update obj is null");
WriteResult result = dbCollection.update(search, updateObj, true, true);
System.out.println(result.toString());
}
public static void update(String dbName, String collectionName,
Object updateObj, Object id) {
DBCollection dbCollection = getDBCollection(dbName, collectionName);
DBObject search = dbCollection.findOne(new BasicDBObject("_id", id));
JSONObject updateJson = JSONObject.fromObject(updateObj);
DBObject updateDBO = (BasicDBObject) JSON.parse(updateJson.toString());
WriteResult result = dbCollection.update(search, updateDBO, true, true);
System.out.println(result.toString());
}
public static <M> M queryByid(final Object id, final Class<M> entityClass,
final String dbName, final String collectionName) {
DBCollection dbCollection = getDBCollection(dbName, collectionName);
DBObject search = dbCollection.findOne(new BasicDBObject("VIN", id));
if (null == search)
return null;
String json = JSON.serialize(search);
JSONObject jObj = JSONObject.fromObject(json);
M obj = (M) JSONObject.toBean(jObj, entityClass);
return obj;
}
public static <M> List<M> query(final Class<M> entityClass,
BasicDBObject query, BasicDBObject orderBy, final String dbName,
final String collectionName, Page page,
Map<String, Class<?>> classMap) {
List<M> list = new ArrayList<M>();
DBCollection collection = getDBCollection(dbName, collectionName);
DBCursor cursor = null;
if (null == query)
cursor = collection.find();
else
cursor = collection.find(query);
int count = cursor.count();
if (page != null) {
if (page.getSumCounts() == 0)
page.reBuildPage(page.getRequest(), page.getCur(), count,
page.getRows());
cursor.skip((page.getCur() - 1) * page.getRows());
cursor.limit(page.getRows());
}
if (null != orderBy)
cursor.sort(orderBy);
while (cursor.hasNext()) {
DBObject obj = cursor.next();
JSONObject jObj = JSONObject.fromObject(obj);
@SuppressWarnings("unchecked")
M m = null;
if (null != classMap)
m = (M) JSONObject.toBean(jObj, entityClass, classMap);
else
m = (M) JSONObject.toBean(jObj, entityClass);
list.add(m);
}
return list;
}
public static <M>int queryCount(final Class<M> entityClass,
BasicDBObject query, BasicDBObject orderBy, final String dbName,
final String collectionName, Page page,
Map<String, Class<?>> classMap) {
DBCollection collection = getDBCollection(dbName, collectionName);
DBCursor cursor = null;
if (null == query)
cursor = collection.find();
else
cursor = collection.find(query);
int count = cursor.count();
return count;
}
public static Integer queryCount(final BasicDBObject query,
final String dbName, final String collectionName) {
DBCollection collection = getDBCollection(dbName, collectionName);
DBCursor cursor = null;
if (null == query)
cursor = collection.find();
else
cursor = collection.find(query);
int count = cursor.count();
return count;
}
private static MongoClientOptions getConfOptions() {
return new MongoClientOptions.Builder().socketKeepAlive(true) // 是否保持长链接
.connectTimeout(5000) // 链接超时时间
.socketTimeout(100000) // read数据超时时间//5000
.readPreference(ReadPreference.primary()) // 最近优先策略
.connectionsPerHost(100) // 每个地址最大请求数
.maxWaitTime(1000 * 60 * 2) // 长链接的最大等待时间
.threadsAllowedToBlockForConnectionMultiplier(50) // 一个socket最大的等待请求数
.writeConcern(WriteConcern.NORMAL).build();
}
public static DB getDB(String dbName) {
return mongoClient.getDB(dbName);
}
public static DBCollection getDBCollection(String dbName,
String collectionName) {
DB db = getDB(dbName);
DBCollection coll = db.getCollection(collectionName);
return coll;
}
public static Mongo getMongoClient() {
return mongoClient;
}
public static final class SORT_TYPE {
/**
* 正序
*/
public static final Integer ASC = 1;
/**
* 倒序
*/
public static final Integer DESC = -1;
}
}