在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

JAVA单例MongoDB工具类

2016-12-20 13:15| 发布者: zhangjf| 查看: 501| 评论: 0

摘要: JAVA驱动版本: !-- MongoDB驱动 -- dependency groupIdorg.mongodb/groupId artifactIdmongo-java-driver/artifactId version3.0.2/version /dependency 复 ...
JAVA驱动版本:
  1. <!-- MongoDB驱动 -->
  2. <dependency>
  3. <groupId>org.mongodb</groupId>
  4. <artifactId>mongo-java-driver</artifactId>
  5. <version>3.0.2</version>
  6. </dependency>
复制代码

工具类代码如下:
  1. package utils;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.apache.commons.configuration.CompositeConfiguration;
  5. import org.apache.commons.configuration.ConfigurationException;
  6. import org.apache.commons.configuration.PropertiesConfiguration;
  7. import org.bson.Document;
  8. import org.bson.conversions.Bson;
  9. import org.bson.types.ObjectId;
  10. import com.mongodb.BasicDBObject;
  11. import com.mongodb.MongoClient;
  12. import com.mongodb.MongoClientOptions;
  13. import com.mongodb.MongoClientOptions.Builder;
  14. import com.mongodb.WriteConcern;
  15. import com.mongodb.client.MongoCollection;
  16. import com.mongodb.client.MongoCursor;
  17. import com.mongodb.client.MongoDatabase;
  18. import com.mongodb.client.MongoIterable;
  19. import com.mongodb.client.model.Filters;
  20. import com.mongodb.client.result.DeleteResult;
  21. /**
  22. * MongoDB工具类 Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了<br>
  23. * 注意Mongo已经实现了连接池,并且是线程安全的。 <br>
  24. * 设计为单例模式, 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,<br>
  25. * Mongo有个内置的连接池(默认为10个) 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,<br>
  26. * DB和DBCollection是绝对线程安全的<br>
  27. *
  28. * @author zhoulingfei
  29. * @date 2015-5-29 上午11:49:49
  30. * @version 0.0.0
  31. * @Copyright (c)1997-2015 NavInfo Co.Ltd. All Rights Reserved.
  32. */
  33. public enum MongoDBUtil {
  34. /**
  35. * 定义一个枚举的元素,它代表此类的一个实例
  36. */
  37. instance;
  38. private MongoClient mongoClient;
  39. static {
  40. System.out.println("===============MongoDBUtil初始化========================");
  41. CompositeConfiguration config = new CompositeConfiguration();
  42. try {
  43. config.addConfiguration(new PropertiesConfiguration("mongodb.properties"));
  44. } catch (ConfigurationException e) {
  45. e.printStackTrace();
  46. }
  47. // 从配置文件中获取属性值
  48. String ip = config.getString("host");
  49. int port = config.getInt("port");
  50. instance.mongoClient = new MongoClient(ip, port);
  51. // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
  52. // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018));
  53. // instance.mongoClient = new MongoClient(listHost);
  54. // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
  55. // boolean auth = db.authenticate(myUserName, myPassword);
  56. Builder options = new MongoClientOptions.Builder();
  57. // options.autoConnectRetry(true);// 自动重连true
  58. // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
  59. options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100
  60. options.connectTimeout(15000);// 连接超时,推荐>3000毫秒
  61. options.maxWaitTime(5000); //
  62. options.socketTimeout(0);// 套接字超时时间,0无限制
  63. options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
  64. options.writeConcern(WriteConcern.SAFE);//
  65. options.build();
  66. }
  67. // ------------------------------------共用方法---------------------------------------------------
  68. /**
  69. * 获取DB实例 - 指定DB
  70. *
  71. * @param dbName
  72. * @return
  73. */
  74. public MongoDatabase getDB(String dbName) {
  75. if (dbName != null && !"".equals(dbName)) {
  76. MongoDatabase database = mongoClient.getDatabase(dbName);
  77. return database;
  78. }
  79. return null;
  80. }
  81. /**
  82. * 获取collection对象 - 指定Collection
  83. *
  84. * @param collName
  85. * @return
  86. */
  87. public MongoCollection<Document> getCollection(String dbName, String collName) {
  88. if (null == collName || "".equals(collName)) {
  89. return null;
  90. }
  91. if (null == dbName || "".equals(dbName)) {
  92. return null;
  93. }
  94. MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
  95. return collection;
  96. }
  97. /**
  98. * 查询DB下的所有表名
  99. */
  100. public List<String> getAllCollections(String dbName) {
  101. MongoIterable<String> colls = getDB(dbName).listCollectionNames();
  102. List<String> _list = new ArrayList<String>();
  103. for (String s : colls) {
  104. _list.add(s);
  105. }
  106. return _list;
  107. }
  108. /**
  109. * 获取所有数据库名称列表
  110. *
  111. * @return
  112. */
  113. public MongoIterable<String> getAllDBNames() {
  114. MongoIterable<String> s = mongoClient.listDatabaseNames();
  115. return s;
  116. }
  117. /**
  118. * 删除一个数据库
  119. */
  120. public void dropDB(String dbName) {
  121. getDB(dbName).drop();
  122. }
  123. /**
  124. * 查找对象 - 根据主键_id
  125. *
  126. * @param collection
  127. * @param id
  128. * @return
  129. */
  130. public Document findById(MongoCollection<Document> coll, String id) {
  131. ObjectId _idobj = null;
  132. try {
  133. _idobj = new ObjectId(id);
  134. } catch (Exception e) {
  135. return null;
  136. }
  137. Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();
  138. return myDoc;
  139. }
  140. /** 统计数 */
  141. public int getCount(MongoCollection<Document> coll) {
  142. int count = (int) coll.count();
  143. return count;
  144. }
  145. /** 条件查询 */
  146. public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
  147. return coll.find(filter).iterator();
  148. }
  149. /** 分页查询 */
  150. public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) {
  151. Bson orderBy = new BasicDBObject("_id", 1);
  152. return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
  153. }
  154. /**
  155. * 通过ID删除
  156. *
  157. * @param coll
  158. * @param id
  159. * @return
  160. */
  161. public int deleteById(MongoCollection<Document> coll, String id) {
  162. int count = 0;
  163. ObjectId _id = null;
  164. try {
  165. _id = new ObjectId(id);
  166. } catch (Exception e) {
  167. return 0;
  168. }
  169. Bson filter = Filters.eq("_id", _id);
  170. DeleteResult deleteResult = coll.deleteOne(filter);
  171. count = (int) deleteResult.getDeletedCount();
  172. return count;
  173. }
  174. /**
  175. * FIXME
  176. *
  177. * @param coll
  178. * @param id
  179. * @param newdoc
  180. * @return
  181. */
  182. public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) {
  183. ObjectId _idobj = null;
  184. try {
  185. _idobj = new ObjectId(id);
  186. } catch (Exception e) {
  187. return null;
  188. }
  189. Bson filter = Filters.eq("_id", _idobj);
  190. // coll.replaceOne(filter, newdoc); // 完全替代
  191. coll.updateOne(filter, new Document("$set", newdoc));
  192. return newdoc;
  193. }
  194. public void dropCollection(String dbName, String collName) {
  195. getDB(dbName).getCollection(collName).drop();
  196. }
  197. /**
  198. * 关闭Mongodb
  199. */
  200. public void close() {
  201. if (mongoClient != null) {
  202. mongoClient.close();
  203. mongoClient = null;
  204. }
  205. }
  206. /**
  207. * 测试入口
  208. *
  209. * @param args
  210. */
  211. public static void main(String[] args) {
  212. String dbName = "GC_MAP_DISPLAY_DB";
  213. String collName = "COMMUNITY_BJ";
  214. MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
  215. // 插入多条
  216. // for (int i = 1; i <= 4; i++) {
  217. // Document doc = new Document();
  218. // doc.put("name", "zhoulf");
  219. // doc.put("school", "NEFU" + i);
  220. // Document interests = new Document();
  221. // interests.put("game", "game" + i);
  222. // interests.put("ball", "ball" + i);
  223. // doc.put("interests", interests);
  224. // coll.insertOne(doc);
  225. // }
  226. // // 根据ID查询
  227. // String id = "556925f34711371df0ddfd4b";
  228. // Document doc = MongoDBUtil2.instance.findById(coll, id);
  229. // System.out.println(doc);
  230. // 查询多个
  231. // MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();
  232. // while (cursor1.hasNext()) {
  233. // org.bson.Document _doc = (Document) cursor1.next();
  234. // System.out.println(_doc.toString());
  235. // }
  236. // cursor1.close();
  237. // 查询多个
  238. // MongoCursor<Person> cursor2 = coll.find(Person.class).iterator();
  239. // 删除数据库
  240. // MongoDBUtil2.instance.dropDB("testdb");
  241. // 删除表
  242. // MongoDBUtil2.instance.dropCollection(dbName, collName);
  243. // 修改数据
  244. // String id = "556949504711371c60601b5a";
  245. // Document newdoc = new Document();
  246. // newdoc.put("name", "时候");
  247. // MongoDBUtil.instance.updateById(coll, id, newdoc);
  248. // 统计表
  249. // System.out.println(MongoDBUtil.instance.getCount(coll));
  250. // 查询所有
  251. Bson filter = Filters.eq("count", 0);
  252. MongoDBUtil.instance.find(coll, filter);
  253. }
  254. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 10:57

Copyright 2015-2025 djqfx

返回顶部