package com.gyee.frame.util.mongodb;


import com.gyee.frame.common.conf.MongodbConfig;
import com.mongodb.*;

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

/**
 * ClassName:ApiEdos <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2016-7-25 下午12:26:14 <br/>
 * 
 * @author 石林
 * @version
 * @since JDK 1.6
 * @see
 */
public class ApiMongoDb {

	private static MongoClient mongoClient = null;
	// 获得配置文件edos ip地址 和端口号
	static String mongodb_ip = MongodbConfig.mongodb_ip;
	static int mongodb_port = Integer.valueOf(MongodbConfig.mongodb_port);
	static int mongodb_perHost = Integer.valueOf(MongodbConfig.mongodb_perHost);
	static int mongodb_threadsAllowed = Integer.valueOf(MongodbConfig.mongodb_threadsAllowed);
	static int mongodb_connectTimeout = Integer.valueOf(MongodbConfig.mongodb_connectTimeout);
	static int mongodb_maxWaitTime = Integer.valueOf(MongodbConfig.mongodb_maxWaitTime);
	static int mongodb_socketTimeout = Integer.valueOf(MongodbConfig.mongodb_socketTimeout);

	private ApiMongoDb() {
	}

	public static MongoClient getInstance() throws Exception {

		if (mongoClient == null) {

			ServerAddress serverAddress = new ServerAddress(mongodb_ip, mongodb_port);
			List<ServerAddress> addrs = new ArrayList<ServerAddress>();
			addrs.add(serverAddress);
			// MongoClientOptions options=new MongoClientOptions();

			WriteConcern writeConcern = new WriteConcern(1, 0);

			MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(mongodb_threadsAllowed).threadsAllowedToBlockForConnectionMultiplier(mongodb_threadsAllowed).connectTimeout(mongodb_connectTimeout).maxWaitTime(mongodb_maxWaitTime)
					// .socketKeepAlive(true)
					.socketTimeout(mongodb_socketTimeout).writeConcern(writeConcern).readPreference(ReadPreference.secondaryPreferred()).build();

			mongoClient = new MongoClient(serverAddress, options);

		}
		return mongoClient;

	}

}
