mongoDB : 2.6
MongoDB Drivers : 2.12.2
Language:Java
package global.db;
import java.net.UnknownHostException;
import java.util.Arrays;
import javassist.bytecode.stackmap.TypeData.ClassName;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
/**
* @author hua
* 處理 mongoDB 基礎連線建立
*/
@Configuration
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class MongoConnection {
private static Logger logger = Logger.getLogger(ClassName.class);
@Value("${mongo.host}")
private String host;
@Value("${mongo.port}")
private int port;
@Value("${mongo.dbName}")
private String dbName;
@Value("${mongo.user}")
private String user;
@Value("${mongo.pwd}")
private String pwd;
private MongoClient mongoClient;
public MongoConnection() throws UnknownHostException {
super();
}
/**
* 建立連線
*/
private void buildConnection()throws UnknownHostException{
try {
MongoCredential credential = MongoCredential.createMongoCRCredential(this.user, this.dbName, this.pwd.toCharArray());
MongoClientOptions options = getOption();
ServerAddress address = new ServerAddress(this.host, this.port);
mongoClient = new MongoClient(address, Arrays.asList(credential), options);
logger.info("--------------------MongoDB 驗證成功");
} catch (UnknownHostException e) {
logger.error("MongoDB 建立連線失敗!");
if(mongoClient != null){
mongoClient.close();
}
throw e;
}
}
//線程等待數量 * 主機最大連線數 = pool 數量
protected MongoClientOptions getOption(){
return new MongoClientOptions.Builder()
.threadsAllowedToBlockForConnectionMultiplier(300) //線程等待的數量
.connectionsPerHost(10) //主機最大連線數
.connectTimeout(5000)
.build();
}
/** 取得DB操作物件
* @return
* @throws UnknownHostException
*/
public DB getDB() throws UnknownHostException {
synchronized (this) {
if(mongoClient == null){
buildConnection();
}
}
return mongoClient.getDB(this.dbName);
}
}
Note :
- mongo 現在版本,建議使用MongoClientOptions 而不要再使用MongoOptions。