1. 程式人生 > >Mongodb連線詳解

Mongodb連線詳解

一、先寫一個配置檔案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>