MongoDB 工具类及简单测试
2017-04-19 15:17
316 查看
因篇幅有限仅贴出添加测试代码。所有代码在篇末提供下载地址。
存在Redis代码,不需要可删除相关的包。
下载地址 : http://download.csdn.net/detail/hq0556/9818252
数据库DB
/* * MongoDB工具类 Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了<br> * 注意Mongo已经实现了连接池,并且是线程安全的。 <br> * 设计为单例模式, 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,<br> * Mongo有个内置的连接池(默认为10个) 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,<br> * DB和DBCollection是绝对线程安全的<br> */ @SuppressWarnings("deprecation") public class MongoDBUtil { protected static MongoClient mongoClient = null; //mongodb服务器IP private static String ADDR = "127.0.0.1"; //mongodb的端口号 private static int PORT = 27017; static { mongoClient = new MongoClient(ADDR, PORT); // 多个mongodb服务器连接如下 // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018)); // mongoClient = new MongoClient(listHost); // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码: // boolean auth = db.authenticate(myUserName, myPassword); Builder options = new MongoClientOptions.Builder(); // options.autoConnectRetry(true);// 自动重连true // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100 options.connectTimeout(15000);// 连接超时,推荐>3000毫秒 options.maxWaitTime(5000); // options.socketTimeout(0);// 套接字超时时间,0无限制 options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。 options.build(); } public static MongoClient getMongoClient() { if(mongoClient == null) mongoClient = new MongoClient(ADDR, PORT); return mongoClient; } /** * 关闭Mongodb */ public static void close() { if (mongoClient != null) { mongoClient.close(); mongoClient = null; } } /** * 获取所有数据库名称列表 * @return 所有数据库名称 */ public static List<String> findAllDBNames() { return mongoClient.getDatabaseNames(); } /** * 获取DB实例 - 指定DB * @param dbName 数据库名 * @return 数据库实例 */ public static MongoDatabase findDB(String dbName) { if (dbName != null && !"".equals(dbName)) { MongoDatabase database = mongoClient.getDatabase(dbName); return database; } return null; } /** * 删除一个数据库 */ public static void dropDB(String dbName) { findDB(dbName).drop(); } }
集合Collection
public class MongoCollectionUtil extends MongoDBUtil { /** * 查询DB下的所有表名 * @param dbName 数据库名 * @return 数据库中表名 */ public static List<String> findAllCollections(String dbName) { MongoIterable<String> colls = findDB(dbName).listCollectionNames(); List<String> _list = new ArrayList<String>(); for (String s : colls) { _list.add(s); } return _list; } /** * 查询DB下的所有表的数量 * @param dbName 库名 * @param collName 集合名 * @return */ public static int findAllDocumentCount(String dbName) { List<String> colls = findAllCollections(dbName); return (int) colls.size(); } /** * 获取某个库下,某个集合中文档数量 * @param dbName 库名 * @param collName 集合名 * @return */ public static int findAllDocumentCount(String dbName, String collName) { MongoCollection<Document> coll = findDB(dbName).getCollection(collName); return (int) coll.count(); } /** * 在库下创建集合 * @param dbName 库名 * @param collName 集合名 * @return */ public static void createCollection(String dbName, String collName) { findDB(dbName).createCollection(collName); } /** * 删除某个库下,某个集合 * @param dbName 库名 * @param collName 集合名 * @return */ public static void dropCollection(String dbName, String collName) { findDB(dbName).getCollection(collName).drop(); } /** * 获取某个库下,某个集合中文档 * @param dbName 库名 * @param collName 集合名 * @return */ public static MongoCollection<Document> findCollection(String dbName, String collName) { if (null == dbName || "".equals(dbName)) return null; if (null == collName || "".equals(collName)) return null; MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName); return collection; } }
文件Document
public class MongoDocumentUtil extends MongoCollectionUtil { /** * 文档集合中添加文档 * @param dbName 库名 * @param collName 集合名 * @param document 文档 */ public static void addDocument(String dbName, String collName, Document document) { addDocument(findCollection(dbName, collName), document); } /** * 文档集合中添加多个文档 * @param dbName 库名 * @param collName 集合名 * @param document 文档 */ public static void addDocument(String dbName, String collName, List<Document> documents) { addDocument(findCollection(dbName, collName), documents); } /** * 文档集合中添加文档 * @param coll 集合文档 * @param document 文档 */ public static void addDocument(MongoCollection<Document> coll, Document document) { List<Document> documents = new ArrayList<Document>(); documents.add(document); addDocument(coll, documents); } /** * 文档集合中添加多个文档 * @param coll 集合文档 * @param documents 多个文档 */ public static void addDocument(MongoCollection<Document> coll, List<Document> documents) { coll.insertMany(documents); } /** * 根据文档Id修改文档 * @param dbName 库名 * @param collName 集合名 * @param id id * @param newdoc 新文档 * @return */ public static Document updateDocumentById(String dbName, String collName, String id, Document newdoc) { return updateDocumentById(findCollection(dbName, collName), id, newdoc); } /** * 根据文档Id修改文档 * @param coll 集合文档 * @param id id * @param newdoc 新文档 * @return */ public static Document updateDocumentById(MongoCollection<Document> coll, String id, Document newdoc) { ObjectId _idobj = null; try { _idobj = new ObjectId(id); } catch (Exception e) { return null; } Bson filter = Filters.eq("_id", _idobj); return updateDocument(coll, filter, newdoc); } /** * 根据文档Id修改文档 * @param coll 集合文档 * @param filter 查询条件 * @param newdoc 新文档 * @return */ public static Document updateDocument(String dbName, String collName, Bson filter, Document newdoc) { return updateDocument(findCollection(dbName, collName), filter, newdoc); } /** * 根据文档Id修改文档 * @param coll 集合文档 * @param filter 查询条件 * @param newdoc 新文档 * @return */ public static Document updateDocument(MongoCollection<Document> coll, Bson filter, Document newdoc) { // coll.replaceOne(filter, newdoc); // 完全替代 coll.updateOne(filter, new Document("$set", newdoc)); return newdoc; } /** * 通过ID删除文档 * @param dbName 库名 * @param collName 集合名 * @param id id * @return */ public static int deleteDocumentById(String dbName, String collName, String id) { return deleteDocumentById(findCollection(dbName, collName), id); } /** * 通过ID删除文档 * @param coll 集合 * @param id id * @return */ public static int deleteDocumentById(MongoCollection<Document> coll, String id) { ObjectId _id = null; try { _id = new ObjectId(id); } catch (Exception e) { return 0; } Bson filter = Filters.eq("_id", _id); return deleteDocument(coll, filter); } /** * 通过ID删除文档 * @param dbName 库名 * @param collName 集合名 * @param filter 查询条件 * @return */ public static int deleteDocument(String dbName, String collName, Bson filter) { return deleteDocument(findCollection(dbName, collName), filter); } /** * 通过ID删除文档 * @param coll 集合 * @param filter 查询条件 * @return */ public static int deleteDocument(MongoCollection<Document> coll, Bson filter) { int count = 0; DeleteResult deleteResult = coll.deleteOne(filter); count = (int) deleteResult.getDeletedCount(); return count; } /** * 查找对象 - 根据主键_id * @param dbName 库名 * @param collName 集合名 * @param id * @return */ public static Document findDocumentById(String dbName, String collName, String id) { return findDocumentById(findCollection(dbName, collName), id); } /** * 查找对象 - 根据主键_id * @param collection 集合 * @param id * @return */ public static Document findDocumentById(MongoCollection<Document> coll, String id) { ObjectId _idobj = null; try { _idobj = new ObjectId(id); } catch (Exception e) { return null; } Document myDoc = coll.find(Filters.eq("_id", _idobj)).first(); return myDoc; } /** * 查找所有文档 * @param dbName 库名 * @param collName 集合名 * @return */ public static List<Document> findAllDocument(String dbName, String collName) { return findAllDocument(findCollection(dbName, collName)); } /** * 查找所有文档 * @param coll 集合文档 * @return */ public static List<Document> findAllDocument(MongoCollection<Document> coll) { Bson orderBy = new BasicDBObject("_id", -1); MongoCursor<Document> mongoCursor = coll.find().sort(orderBy).iterator(); List<Document> result = new ArrayList<Document>(); while(mongoCursor.hasNext()){ result.add(mongoCursor.next()); } return result; } /** * 查找所有文档 * @param dbName 库名 * @param collName 集合名 * @param orderBy 排序条件 * @return */ public static List<Document> findAllDocument(String dbName, String collName, Bson orderBy) { return findAllDocument(findCollection(dbName, collName),orderBy); } /** * 查找所有文档 * @param coll 集合文档 * @param orderBy 排序条件 * @return */ public static List<Document> findAllDocument(MongoCollection<Document> coll, Bson orderBy) { MongoCursor<Document> mongoCursor = coll.find().sort(orderBy).iterator(); List<Document> result = new ArrayList<Document>(); while(mongoCursor.hasNext()){ result.add(mongoCursor.next()); } return result; } /** * 根据条件查找文档 * @param dbName 库名 * @param collName 集合名 * @param filter 查询条件 * @return */ public static List<Document> findDocument(String dbName, String collName, Bson filter) { return findDocument(findCollection(dbName, collName), filter); } /** * 根据条件查找文档 * @param coll 集合文档 * @param filter 查询条件 * @return */ public static List<Document> findDocument(MongoCollection<Document> coll, Bson filter) { Bson orderBy = new BasicDBObject("_id", -1); MongoCursor<Document> mongoCursor = coll.find(filter).sort(orderBy).iterator(); List<Document> result = new ArrayList<Document>(); while(mongoCursor.hasNext()){ result.add(mongoCursor.next()); } return result; } /** * 根据条件查找文档 * @param dbName 库名 * @param collName 集合名 * @param filter 查询条件 * @param orderBy 排序条件 * @return */ public static List<Document> findDocument(String dbName, String collName, Bson filter, Bson orderBy) { return findDocument(findCollection(dbName, collName), filter, orderBy); } /** * 根据条件查找文档 * @param coll 集合文档 * @param filter 查询条件 * @param orderBy 排序条件 * @return */ public static List<Document> findDocument(MongoCollection<Document> coll, Bson filter, Bson orderBy) { MongoCursor<Document> mongoCursor = coll.find(filter).sort(orderBy).iterator(); List<Document> result = new ArrayList<Document>(); while(mongoCursor.hasNext()){ result.add(mongoCursor.next()); } return result; } /** * 分页查询文档 * @param dbName 库名 * @param collName 集合名 * @param filter 条件查询 * @param orderBy 排序查询 * @param pageNo 页数 * @param pageSize 每页数量 * @return */ public static List<Document> findDocumentByPage(String dbName, String collName, Bson filter, Bson orderBy, int pageNo, int pageSize) { return findDocumentByPage(findCollection(dbName, collName), filter, orderBy, pageNo, pageSize); } /** * 分页查询文档 * @param coll 集合文档 * @param filter 条件查询 * @param orderBy 排序查询 * @param pageNo 页数 * @param pageSize 每页数量 * @return */ public static List<Document> findDocumentByPage(MongoCollection<Document> coll, Bson filter, Bson orderBy, int pageNo, int pageSize) { if(orderBy == null) orderBy = new BasicDBObject("_id", -1); MongoCursor<Document> mongoCursor = coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator(); List<Document> result = new ArrayList<Document>(); while(mongoCursor.hasNext()){ result.add(mongoCursor.next()); } return result; } }
文件
@SuppressWarnings("deprecation") public class MonogoGridFSUtil extends MongoDBUtil { GridFS gridFS = null; public MonogoGridFSUtil(String dbName) { DB db = MongoDBUtil.getMongoClient().getDB(dbName); gridFS = new GridFS(db); } /** * 将文件保存在MongoDB中 * @param file 文件 * @return 是否成功 */ public boolean write(File file){ return write(file.getAbsolutePath(), file.getName()); } /** * 将文件保存在MongoDB中 * @param filePath 文件地址 * @param fileName 文件名 * @return 是否成功 */ public boolean write(String filePath, String fileName){ File file =new File(filePath+"/"+fileName); if(!file.exists()) return false; try { Object id = System.currentTimeMillis(); DBObject query = new BasicDBObject("_id", id); GridFSDBFile gridFSDBFile = gridFS.findOne(query); if(gridFSDBFile == null){ GridFSInputFile gridFSInputFile = gridFS.createFile(file); gridFSInputFile.setId(id); gridFSInputFile.setFilename(fileName); gridFSInputFile.save(); } } catch(Exception e) { e.printStackTrace(); return false; } return true; } /** * 将保存在MongoDB中的文件输出到指定地址 * @param filePath 文件地址 * @param fileName 文件名 * @return 是否成功 */ public boolean read(String filePath, String fileName){ GridFSDBFile gridFSDBFile = getByFileName(fileName); return read(gridFSDBFile, filePath, fileName); } /** * 将保存在MongoDB中的文件输出到指定地址 * @param gridFSDBFile DB文件 * @param filePath 文件地址 * @param fileName 文件名 * @return 是否成功 */ public boolean read(GridFSDBFile gridFSDBFile, String filePath, String fileName){ if(gridFSDBFile != null){ try { gridFSDBFile.writeTo(new FileOutputStream(filePath+"/"+fileName)); } catch(Exception e) { e.printStackTrace(); return false; } return true; } return false; } /** * 据id返回文件 * @param id * @return */ public GridFSDBFile getById(Object id){ DBObject query = new BasicDBObject("_id", id); GridFSDBFile gridFSDBFile = gridFS.findOne(query); return gridFSDBFile; } /** * 据文件名返回文件,只返回第一个 * @param fileName * @return */ public GridFSDBFile getByFileName(String fileName){ DBObject query = new BasicDBObject("filename", fileName); GridFSDBFile gridFSDBFile = gridFS.findOne(query); return gridFSDBFile; } /** * 根据文件名删除文件 * @param fileName 文件名 * @return */ public void deleteByFileName(String fileName){ gridFS.remove(fileName); } /** * 根据文件Id删除文件 * @param id 文件Id * @return */ public void deleteByFileId(String id){ gridFS.remove(id); } }
测试添加
public class TestAdd { String dbName = "Demo_NoSql"; String collName = "hqTest"; // @Test public void addCollection() { MongoDocumentUtil.createCollection(dbName, collName); } @Test public void addDocument() { Document document = new Document("name", "heqing"). append("age", 27). append("e_mail", "975656343@qq.com"). append("address", "安徽/安庆"); MongoDocumentUtil.addDocument(dbName, collName, document); List<Document> documents = new ArrayList<>(); Document document1 = new Document("name", "heqing1"). append("age", 26). append("e_mail", "975656343@qq.com"). append("address", "安徽/安庆"); Document document2 = new Document("name", "heqing2"). append("age", 27). append("e_mail", "975656343@qq.com"). append("address", "安徽/安庆"); documents.add(document1);documents.add(document2); MongoCollection<Document> colls = MongoDocumentUtil.findCollection(dbName, collName); MongoDocumentUtil.addDocument(colls, documents); } }
示例代码
本代码中不排除存在错误,望指出。存在Redis代码,不需要可删除相关的包。
下载地址 : http://download.csdn.net/detail/hq0556/9818252
相关文章推荐
- MongoDB的学习与应用一:安装并简单测试MongoDB
- Mongodb 副本集 数据同步简单测试
- C++简单测试MongoDB性能
- MongoDB入库、更新、查询效率简单测试
- MongoDB的学习与应用一:安装并简单测试MongoDB
- NodeJS+Express+mongoDB简单测试
- flask bottle gunicorn gevent meinheld 组合测试性能(简单读写mongodb)
- Mongodb简单的分片搭建与测试
- 利用ab测试工具对Tornado下使用mongodb驱动的性能简单测试分析
- php下MongoDB扩展的安装和简单测试
- MongoDB 副本集和C#交互,简单测试
- mongodb效率的简单测试
- MongoDB的简单QPS测试(单机)
- MongoDB简单测试
- styleman_network 网络引擎性能简单测试
- JMeter 进行简单的API测试
- mongodb的安装和简单使用
- C++ 之Boost 实用工具类及简单使用
- 高德地图的Js API 简单Demo,可以快速实现路点描线(摘自官方接口及自行修改测试)
- JS简单封装的图片无缝滚动效果示例【测试可用】