一、先写一个配置文件mongodb.properties
mongo.default.ip=192.168.3.71
#端口,默认27017
mongo.default.port=27017
#连接池大小,默认10
mongo.default.poolsize=10
#等待连接大小,默认10
mongo.default.blocksize=10
#默认的数据库名,该值无默认值,如果通过无dbname获取db,必须设置此值
mongo.default.defaultdb=njrc
导入的主要jar包:mongo-2.10.1.jar、spring-beans-3.2.12.RELEASE.jar(InitializingBean类)、commons-lang-2.6.jar、log4j-1.2.17.jar、rt.jar等
二、然后写一个接口文件
package com.mongodb.api;
import com.mongodb.DB;
import com.mongodb.Mongo;
public interface MongoManager {
/**
* 返回configname=default,并且default中配置了defaultdb的DB对象
*
* @return
*/
public DB getDB();
/**
* 返回configname=default,db名字为dbname的DB对象
*
* @param dbname
* @return
*/
public DB getDB(String dbname);
/**
* 返回配置名为configname,并且该配置中配置了defaultdb的DB对象
*
* @param configname
* @return
*/
public DB getDBByConfigName(String configname);
/**
* 返回配置名为configname,db名字为dbname的DB对象
*
* @param configname
* @param dbname
* @return
*/
public DB getDB(String configname, String dbname);
/**
* 返回configname=default的mongo对象
*
* @return
*/
public Mongo getMongo();
/**
* 返回配置名为configname的mongo对象
*
* @param configname
* @return
*/
public Mongo getMongo(String configname);
}
三、之后写一个实现类
package com.mongodb.internal.impl;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.api.MongoManager;
public class MongoManagerImpl implements MongoManager,InitializingBean{
private static final Logger logger = Logger.getLogger(MongoManagerImpl.class);
private Map<String, Mongo> ms = new HashMap<String, Mongo>();
private Map<String, String> ns = new HashMap<String, String>();
private String DEFAULT = "default";
private int DEFPORT = 27017;
private int DEFPOOL = 10;
private int DEFBLOCK = 10;
private String configFile = "mongodb.properties";
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
@Override
public void afterPropertiesSet() throws Exception {
final Map<String, Map<String, String>> tmp = new HashMap<String, Map<String, String>>();
try {
final InputStream in = MongoManagerImpl.class.getResourceAsStream("/" + this.configFile);
final Properties prop = new Properties();
prop.load(in);
for (Object k : prop.keySet()) {
String[] key = StringUtils.split((String) k, ".");
if (key.length != 3
|| !key[0].equals("mongo")
|| (!key[2].equals("ip") && !key[2].equals("port") && !key[2].equals("poolsize") && !key[2].equals("blocksize") && !key[2]
.equals("defaultdb"))) {
continue;
}
if (!tmp.containsKey(key[1])) {
tmp.put(key[1], new HashMap<String, String>());
}
if (key[2].equals("ip")) {
tmp.get(key[1]).put("ip", prop.getProperty((String) k));
} else if (key[2].equals("port")) {
tmp.get(key[1]).put("port", prop.getProperty((String) k));
} else if (key[2].equals("poolsize")) {
tmp.get(key[1]).put("poolsize", prop.getProperty((String) k));
} else if (key[2].equals("blocksize")) {
tmp.get(key[1]).put("blocksize", prop.getProperty((String) k));
} else if (key[2].equals("defaultdb")) {
tmp.get(key[1]).put("defaultdb", prop.getProperty((String) k));
}
}
in.close();
} catch (Exception e) {
logger.error("读取mongodb配置文件错误!", e);
}
for (String configname : tmp.keySet()) {
if (StringUtils.isBlank(tmp.get(configname).get("ip"))) {
logger.error("Mongo配置名:[ " + configname + " ]未配置ip,该配置无效!");
continue;
}
try {
logger.info("Mongo配置名:[ " + configname + " ]正在尝试连接...");
int port = StringUtils.isBlank(tmp.get(configname).get("port")) ? DEFPORT : new Integer(tmp.get(configname).get("port"));
int poolSize = StringUtils.isBlank(tmp.get(configname).get("poolsize")) ? DEFPOOL : new Integer(tmp.get(configname).get("poolsize"));
int blockSize = StringUtils.isBlank(tmp.get(configname).get("blocksize")) ? DEFBLOCK : new Integer(tmp.get(configname).get(
"blocksize"));
final Mongo mongo = new Mongo(tmp.get(configname).get("ip"), port);
MongoOptions opt = mongo.getMongoOptions();
opt.connectionsPerHost = poolSize;
opt.threadsAllowedToBlockForConnectionMultiplier = blockSize;
mongo.getDatabaseNames();
if (StringUtils.isNotBlank(tmp.get(configname).get("defaultdb"))) {
ns.put(configname, tmp.get(configname).get("defaultdb"));
}
ms.put(configname, mongo);
logger.info("Mongo配置名:[ " + configname + " ]已连接");
} catch (Exception e) {
logger.error("Mongo配置名:[ " + configname + " ]无法连接!", e);
}
}
}
@Override
public DB getDB(String dbname) {
if (ms.containsKey(DEFAULT)) {
return ms.get(DEFAULT).getDB(dbname);
}
return null;
}
@Override
public DB getDB(String configname, String dbname) {
if (ms.containsKey(configname)) {
return ms.get(configname).getDB(dbname);
}
return null;
}
@Override
public DB getDB() {
if (ms.containsKey(DEFAULT) && ns.containsKey(DEFAULT)) {
return ms.get(DEFAULT).getDB(ns.get(DEFAULT));
}
return null;
}
@Override
public Mongo getMongo() {
return ms.get(DEFAULT);
}
@Override
public Mongo getMongo(String configname) {
return ms.get(configname);
}
@Override
public DB getDBByConfigName(String configname) {
if (ms.containsKey(configname) && ns.containsKey(configname)) {
return ms.get(configname).getDB(ns.get(configname));
}
return null;
}
}
初始化srping时的配置文件spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="com.mongodb.internal.impl.MongoManagerImpl">
<property name="configFile" value="mongodb.properties" />
</bean>
</beans>
版权声明:本文为zl834205311原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。