菜单

www.2138.com:java实现mongodb的数据库连接池,Java操作MongoDB数据库示例分享

2020年2月15日 - www.2138.com

MongoDB是三个文书档案型数据库,是NOSQL亲族中最根本的成员之风流洒脱,以下代码封装了MongoDB的基本操作。

MongoDB是在于关周全据库和非关全面据库之间的大器晚成种产品,文件的存款和储蓄格式为BSON(意气风发种JSON的恢弘),这里就至关心尊崇要介绍Java通过使用mongo-2.7.3.jar包达成mongodb连接池,具体的java代码完结如下:

www.2138.com,MongoDBConfig.java

数据库连接池配置参数:

package com.posoftframework.mongodb;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Enumeration;import java.util.HashMap;import java.util.Hashtable;import java.util.List;import java.util.Map;import java.util.Properties;import com.mongodb.DB;import com.mongodb.Mongo;/** * MongoDB配置类 * * @author yongtree * @date 2010-7-7 下午07:45:08 * @version 1.0 */public class MongoDBConfig { private static Mongo mongo; private static DB db; private static final String MONGO_DB_ADDRESS = "localhost"; private static final int MONGO_DB_PORT = 27017; private static final String MONGO_DB_USERNAME = "root"; private static final String MONGO_DB_PASSWORD = "root"; private static final String MONGO_DB_DBNAME = "mongodb"; private static final String MONGO_DB_RESOURCE_FILE = "mongodb.cfg.properties"; /** * Mongo数据库参数 */ private static MapString, String cfgMap = new HashMapString, String(); private static HashtableString, DB mongoDBs = new HashtableString, DB(); /** * 初始化Mongo的数据库 */ static { init(); } public static File getConfigFile() { String path = MongoDBConfig.class.getResource("/").getPath(); String fileName = path + MONGO_DB_RESOURCE_FILE; File file = new File(fileName); if (file.exists()) { return file; } return null; } @SuppressWarnings("unchecked") private static void initCfgMap() { File file = getConfigFile(); if (file != null) { Properties p = new Properties(); try { p.load(new FileInputStream(file)); for (Enumeration enu = p.propertyNames(); enu.hasMoreElements();) { String key = (String) enu.nextElement(); String value = (String) p.getProperty(key); cfgMap.put(key, value); } } catch (IOException e) { System.out.println("记载Mongo配置文件失败!"); e.printStackTrace(); } } else { cfgMap.put("mongo.db.address", MONGO_DB_ADDRESS); cfgMap.put("mongo.db.port", String.valueOf(MONGO_DB_PORT)); cfgMap.put("mongo.db.username", MONGO_DB_USERNAME); cfgMap.put("mongo.db.password", MONGO_DB_PASSWORD); cfgMap.put("mongo.db.dbname", MONGO_DB_DBNAME); } } /** * 初始化Mongo数据库 */ private static void init() { initCfgMap(); try { String address = cfgMap.get("mongo.db.address"); int port = Integer.parseInt(cfgMap.get("mongo.db.port").toString()); String dbName = cfgMap.get("mongo.db.dbname"); String username = cfgMap.get("mongo.db.username"); String password = cfgMap.get("mongo.db.password"); mongo = new Mongo(address, port); if (dbName != null && !"".equals(dbName)) { db = mongo.getDB(dbName); if (username != null && !"".equals(username)) { db.addUser(username, password.toCharArray()); } mongoDBs.put(dbName, db); } } catch (IOException e) { e.printStackTrace(); } } /** * 得到Mongo的实例 * * @return */ public static Mongo getMongo() { return mongo; } /** * 得到Mongo的图片数据库 * * @return */ public static DB getDB() { return db; } public static ListString getDBNames() { return mongo.getDatabaseNames(); } /** * 根据数据库名称,得到数据库br/ * 如果不存在,则创建一个该名称的数据库,并设置用户名和密码为配置文件中的参数值/br * * @param dbName * @return */ public static DB getDBByName(String dbName) { DB db = mongo.getDB(dbName); if (!mongoDBs.contains(db)) { db.addUser(cfgMap.get("mongo.db.username"), cfgMap.get( "mongo.db.password").toCharArray()); mongoDBs.put(dbName, db); } return db; }}
 /** 
 *@Description: mongo连接池配置文件 
 */ 
package cn.lulei.mongo.pool; 

public class MongoConfig { 

 private static String userName;//用户名 
 private static String pwd;//密码 
 private static String[] host;//主机地址 
 private static int[] port;//端口地址 
 private static String dbName;//数据库名 
 private static int connectionsPerHost = 20;//每台主机最大连接数 
 private static int threadsAllowedToBlockForConnectionMultiplier = 10;//线程队列数 
 private static boolean authentication = false;//是否需要身份验证 

 public static String getUserName() { 
  return userName; 
 } 
 public static void setUserName(String userName) { 
  MongoConfig.userName = userName; 
 } 
 public static String getPwd() { 
  return pwd; 
 } 
 public static void setPwd(String pwd) { 
  MongoConfig.pwd = pwd; 
 } 
 public static String[] getHost() { 
  return host; 
 } 
 public static void setHost(String[] host) { 
  MongoConfig.host = host; 
 } 
 public static int[] getPort() { 
  return port; 
 } 
 public static void setPort(int[] port) { 
  MongoConfig.port = port; 
 } 
 public static String getDbName() { 
  return dbName; 
 } 
 public static void setDbName(String dbName) { 
  MongoConfig.dbName = dbName; 
 } 
 public static int getConnectionsPerHost() { 
  return connectionsPerHost; 
 } 
 public static void setConnectionsPerHost(int connectionsPerHost) { 
  MongoConfig.connectionsPerHost = connectionsPerHost; 
 } 
 public static int getThreadsAllowedToBlockForConnectionMultiplier() { 
  return threadsAllowedToBlockForConnectionMultiplier; 
 } 
 public static void setThreadsAllowedToBlockForConnectionMultiplier( 
   int threadsAllowedToBlockForConnectionMultiplier) { 
  MongoConfig.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; 
 } 
 public static boolean isAuthentication() { 
  return authentication; 
 } 
 public static void setAuthentication(boolean authentication) { 
  MongoConfig.authentication = authentication; 
 } 
} 

MongoService.java

数据库连接池管理类:

/************************* 版权声明 ********************************* * * * 版权所有:百洋软件 * * Copyright (c) 2010 by  * * * ************************* 变更记录 ********************************* * * 创建者:yongtree 创建日期: 2010-7-7 * 备注: * * 修改者: 修改日期: * 备注: * */package com.posoftframework.mongodb;import java.util.List;import java.util.Map;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;/** * 操作MongoDB的DAO接口 * * @author yongtree * @date 2010-7-7 下午04:44:43 * @version 1.0 */public interface MongoService { public abstract DBCollection getCollection(); /** * 根据数据集合的Map,插入数据 map的key对应数据库中的DBCollection的key值 * * @param obj */ public abstract DBObject insert(DBObject obj); /** * 根据ListMapString,Object结构的数据集合,插入数据 * * @param list */ public abstract void insertBatch(ListDBObject list); /** * 按照条件参数集合map,删除数据 * * @param map */ public abstract void delete(DBObject obj); /** * 按照多种条件的并集,批量删除数据 * * @param list */ public abstract void deleteBatch(ListDBObject list); /** * 得到Collection()总的记录数 * * @return */ public abstract long getCollectionCount(); public abstract long getCount(DBObject query); public abstract ListDBObject find(DBObject query); public abstract ListDBObject find(DBObject query,DBObject sort); public abstract ListDBObject find(DBObject query,DBObject sort,int start,int limit); /** * 根据whereFields参数,更新setFields值 * * @param setFields * @param whereFields */ public abstract void update(DBObject setFields, DBObject whereFields); public abstract ListDBObject findAll(); /** * 根据ID找到唯一数据 有1个id字段标记 * * @param id * @return */ public abstract DBObject getById(String id); /** * 获取所有数据库名称 * * @return */ public ListString getAllDBNames(); public abstract String getDbName(); public abstract void setDbName(String dbName); public abstract DB getDb(); public abstract String getCollName(); public abstract void setCollName(String collName);}
 /** 
 *@Description: mongo数据库连接池管理类 
 */ 
package cn.lulei.mongo.pool; 

import java.util.ArrayList; 
import java.util.List; 

import com.mongodb.DB; 
import com.mongodb.DBCollection; 
import com.mongodb.Mongo; 
import com.mongodb.MongoOptions; 
import com.mongodb.ReadPreference; 
import com.mongodb.ServerAddress; 

public class MongoManager { 

 private static Mongo mongo; 
 private DB db; 

 static{ 
  init(); 
 } 

 /** 
 * @param dbName 
 * @param userName 
 * @param pwd 
 * 实例化dbName一个DB 
  */ 
 public MongoManager(String dbName, String userName, String pwd) { 
  if (dbName == null || "".equals(dbName)) { 
   throw new NumberFormatException("dbName is null"); 
  } 
  db = mongo.getDB(dbName); 
  if(MongoConfig.isAuthentication() && !db.isAuthenticated()){ 
   if (userName == null || "".equals(userName)) { 
    throw new NumberFormatException("userName is null"); 
   } 
   if (pwd == null || "".equals(pwd)) { 
    throw new NumberFormatException("pwd is null"); 
   } 
   db.authenticate(userName, pwd.toCharArray()); 
  } 
 } 

 /** 
  * 使用配置参数实例化 
  */ 
 public MongoManager() { 
  this(MongoConfig.getDbName(), MongoConfig.getUserName(), MongoConfig.getPwd()); 
 } 

 /** 
  * @param tableName 
  * @return 
  * @Description: 获取表tableName的链接DBCollection 
  */ 
 public DBCollection getDBCollection(String tableName) { 
  return db.getCollection(tableName); 
 } 

 /** 
  * @Description: mongo连接池初始化 
  */ 
 private static void init() { 
  if (MongoConfig.getHost() == null || MongoConfig.getHost().length == 0) { 
   throw new NumberFormatException("host is null"); 
  } 
  if (MongoConfig.getPort() == null || MongoConfig.getPort().length == 0) { 
   throw new NumberFormatException("port is null"); 
  } 
  if (MongoConfig.getHost().length != MongoConfig.getPort().length) { 
   throw new NumberFormatException("host's length is not equals port's length"); 
  } 
  try { 
   //服务列表 
   List<ServerAddress> replicaSetSeeds = new ArrayList<ServerAddress>(); 
   for (int i = 0; i < MongoConfig.getHost().length; i++) { 
    replicaSetSeeds.add(new ServerAddress(MongoConfig.getHost()[i], MongoConfig.getPort()[i])); 
   } 
   //连接池参数设置 
   MongoOptions options = new MongoOptions(); 
   options.connectionsPerHost = MongoConfig.getConnectionsPerHost(); 
   options.threadsAllowedToBlockForConnectionMultiplier = MongoConfig.getThreadsAllowedToBlockForConnectionMultiplier(); 
   mongo = new Mongo(replicaSetSeeds, options); 
   //从服务器可读 
   mongo.setReadPreference(ReadPreference.SECONDARY); 
  } catch (Exception e){ 
   e.printStackTrace(); 
  } 
 } 
} 

MongoServiceImpl.java

下边通过二个简易的测量检验类,来看下怎么着接收那个连接池~

/************************* 版权声明 ********************************* * * * 版权所有:百洋软件 * * Copyright (c) 2010 by  * * * ************************* 变更记录 ********************************* * * 创建者:yongtree 创建日期: 2010-7-7 * 备注: * * 修改者: 修改日期: * 备注: * */package com.posoftframework.mongodb;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.bson.types.ObjectId;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.DBObject;/** * * @author yongtree * @date 2010-7-7 下午07:22:15 * @version 1.0 */public class MongoServiceImpl implements MongoService { private String dbName; private String collName; private DB db; public MongoServiceImpl(String dbName, String collName) { this.dbName = dbName; this.collName = collName; try { db = MongoDBConfig.getDBByName(this.dbName); } catch (Throwable e) { e.printStackTrace(); } } public MongoServiceImpl() { getDb(); } public DBCollection getCollection() { return db.getCollection(this.collName); } public DBObject map2Obj(MapString, Object map) { DBObject obj = new BasicDBObject(); if (map.containsKey("class") && map.get("class") instanceof Class) map.remove("class"); obj.putAll(map); return obj; } public DBObject insert(DBObject obj) { getCollection().insert(obj); return obj; } public void insertBatch(ListDBObject list) { if (list == null || list.isEmpty()) { return; } ListDBObject listDB = new ArrayListDBObject(); for (int i = 0; i  list.size(); i++) { listDB.add(list.get(i)); } getCollection().insert(listDB); } public void delete(DBObject obj) { getCollection().remove(obj); } public void deleteBatch(ListDBObject list) { if (list == null || list.isEmpty()) { return; } for (int i = 0; i  list.size(); i++) { getCollection().remove(list.get(i)); } } public long getCollectionCount() { return getCollection().getCount(); } public long getCount(DBObject obj) { if (obj != null) return getCollection().getCount(obj); return getCollectionCount(); } public ListDBObject find(DBObject obj) { DBCursor cur = getCollection().find(obj); return DBCursor2list(cur); } @Override public ListDBObject find(DBObject query, DBObject sort) { DBCursor cur; if (query != null) { cur = getCollection().find(query); } else { cur = getCollection().find(); } if (sort != null) { cur.sort(sort); } return DBCursor2list(cur); } @Override public ListDBObject find(DBObject query, DBObject sort, int start, int limit) { DBCursor cur; if (query != null) { cur = getCollection().find(query); } else { cur = getCollection().find(); } if (sort != null) { cur.sort(sort); } if (start == 0) { cur.batchSize(limit); } else { cur.skip(start).limit(limit); } return DBCursor2list(cur); } private ListDBObject DBCursor2list(DBCursor cur) { ListDBObject list = new ArrayListDBObject(); if (cur != null) { list = cur.toArray(); } return list; } public void update(DBObject setFields, DBObject whereFields) { getCollection().updateMulti(setFields, whereFields); } public ListDBObject findAll() { DBCursor cur = getCollection().find(); ListDBObject list = new ArrayListDBObject(); if (cur != null) { list = cur.toArray(); } return list; } public DBObject getById(String id) { DBObject obj = new BasicDBObject(); obj.put("_id", new ObjectId(id)); DBObject result = getCollection().findOne(obj); return result; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; this.db = MongoDBConfig.getDBByName(this.dbName); } public String getCollName() { return collName; } public void setCollName(String collName) { this.collName = collName; } public DB getDb() { if (this.db == null) { if (this.dbName == null) { this.db = MongoDBConfig.getDB(); } else { this.db = MongoDBConfig.getDBByName(this.dbName); } } return this.db; } public ListString getAllDBNames() { return MongoDBConfig.getDBNames(); }}
 /** 
 *@Description:mongo测试 
 */ 
package cn.lulei.mongo.test; 

import cn.lulei.mongo.pool.MongoConfig; 
import cn.lulei.mongo.pool.MongoManager; 

public class Test { 

 public static void main(String[] args) { 
  // TODO Auto-generated method stub 
  String[] host = {"127.0.0.1"}; 
  int[] port = {27001}; 
  MongoConfig.setHost(host); 
  MongoConfig.setPort(port); 
  MongoConfig.setDbName("novel"); 
  MongoManager mongoManager = new MongoManager(); 
  mongoManager.getDBCollection("chapter"); 
 } 

} 

在动用上述管理类时,只必要起首化MongoConfig类就可以。对类MongoManager的实例话,不仅可以够使用MongoConfig的配置也能够温和通过参数来安装,每一回获得DBCollection
时,只必要调用getDBCollection(String tableNameState of Qatar方法就可以。

以上便是本文的全体内容,希望本文所述对我们学习java程序设计具备助于。

您大概感兴趣的小说:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图