MongoDB数据库连接

1.添加配置文件

#db params

#server=Chinese
server=English

#test数据库
DBUrl=***
DBPort=***
DBName=gameserver

#简体服务器阿里云数据库
#DBUrl=dds-***************.mongodb.rds.aliyuncs.com
#DBPort=****
#DefaultDB=admin
#DBName=***
#username=***
#password=***

#Collection
PVPRecordCollectionName=pvp_record
PVPDataCollectionName=pvp_data
#最大连接数
connectionsPerHost=100
#最大等待时间
maxWaitTime=300000
#连接超时时间
socketTimeout=100000
#连接池最长生命时间
maxConnectionLifeTime=150000
#连接超时时间
connectTimeout=25000
#IP地址查询接口
#ipSearchUrl=http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=
ipSearchUrl=http://ip.taobao.com/service/getIpInfo.php?ip=
#ipSearchUrl=http://ip-api.com/json/



2.配置MongoDB数据库连接类

package util;

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

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBUtil {
	private static MongoClient mongoClient;
	private static MongoDatabase mongoDB;
	
	// 读取配置文件
	private static Properties p = new Properties();	
	
	private final static MongoDBUtil instance = new MongoDBUtil();
	
	public static MongoDBUtil getInstance(){
		return instance;
	}
	
	public static String getSystemParamKeyValue(String key){
		return p.getProperty(key);
	}
	
	public MongoDatabase getMongoDataBase(){
		return mongoDB;
	}
	
	//离线消息集合
	public MongoCollection getOffCollection(){
		return mongoDB.getCollection(p.getProperty("OffCollectionName"));
	}
	//PVP单条记录集合
	public MongoCollection getPVPRecordCollection(){
		return mongoDB.getCollection(p.getProperty("PVPRecordCollectionName"));
	}
	//PVP计数集合
	public MongoCollection getPVPDataCollection(){
		return mongoDB.getCollection(p.getProperty("PVPDataCollectionName"));
	}
	
	public MongoDBUtil(){	
		//String myFilePath = MongoInit.class.getResource("/").getPath() + "db.properties";
		try {
			p.load(MongoDBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
			String DBUrl = p.getProperty("DBUrl");
			String DBName = p.getProperty("DBName");
			int DBPort = Integer.parseInt(p.getProperty("DBPort"));
			
			MongoClientOptions.Builder buide = new MongoClientOptions.Builder();
			buide.connectionsPerHost(Integer.parseInt(p.getProperty("connectionsPerHost")));// 与目标数据库可以建立的最大链接数
			buide.connectTimeout(Integer.parseInt(p.getProperty("connectTimeout")));// 与数据库建立链接的超时时间
			buide.maxWaitTime(Integer.parseInt(p.getProperty("maxWaitTime")));// 一个线程成功获取到一个可用数据库之前的最大等待时间
			buide.threadsAllowedToBlockForConnectionMultiplier(100);
			buide.maxConnectionIdleTime(0);
			buide.maxConnectionLifeTime(Integer.parseInt(p.getProperty("maxConnectionLifeTime")));
			buide.socketTimeout(Integer.parseInt(p.getProperty("socketTimeout")));
			buide.socketKeepAlive(true);
			MongoClientOptions myOptions = buide.build();
			
//			MongoClientOptions myOptions = MongoClientOptions.builder()
//					.connectionsPerHost(Integer.parseInt(p.getProperty("connectionsPerHost")))
//					.maxWaitTime(Integer.parseInt(p.getProperty("maxWaitTime")))
//					.socketTimeout(Integer.parseInt(p.getProperty("socketTimeout")))
//					.maxConnectionLifeTime(Integer.parseInt(p.getProperty("maxConnectionLifeTime")))
//					.connectTimeout(Integer.parseInt(p.getProperty("connectTimeout"))).build();
			
			System.out.println(p.getProperty("server"));
			if(p.getProperty("server").equals("Chinese")){
				
				mongoClient = createMongoDBClient(DBUrl, DBPort);
//				mongoClient = createMongoDBClientWithURI(DBUrl, DBPort);
				
			}else{
				ServerAddress serverAddress = new ServerAddress(DBUrl, DBPort);
				mongoClient = new MongoClient(serverAddress, myOptions);
				
			}
			
			System.out.println("Connect to mongo successfully");
			   
			mongoDB = mongoClient.getDatabase(DBName);
			System.out.println("Connect to mongoDB successfully : "+mongoDB.getName());
		} catch (Exception e) {
		   e.printStackTrace();
		   System.out.println("连接超时!");
		  //手动close释放连接
		   mongoClient.close();
		}
	}
	
	/*
	 * 阿里云,第一种办法
	 */
	public MongoClient createMongoDBClient(String DBUrl, int DBPort){
		ServerAddress serverAddress = new ServerAddress(DBUrl, DBPort);  
        List addrs = new ArrayList();  
        addrs.add(serverAddress);  
          
        String username = p.getProperty("username");
		String password = p.getProperty("password");
		String defaultDB = p.getProperty("DefaultDB");
        //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码  
        MongoCredential credential = MongoCredential.createScramSha1Credential(username, defaultDB, password.toCharArray());
        List credentials = new ArrayList();  
        credentials.add(credential);  
        
        return new MongoClient(addrs,credentials);  
	}
	
	/*
	 * 阿里云,第二种办法
	 */
	public MongoClient createMongoDBClientWithURI(String DBUrl, int DBPort) {
		ServerAddress serverAddress = new ServerAddress(DBUrl, DBPort);  
		String username = p.getProperty("username");
		String password = p.getProperty("password");
		String defaultDB = p.getProperty("DefaultDB");
        //另一种通过URI初始化
        //mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
		String url = "mongodb://" + username + ":" + password + "@" + serverAddress + "/" + defaultDB;
		System.out.println(url);
        MongoClientURI connectionString = new MongoClientURI(url);
        return new MongoClient(connectionString);
    }
	
}

注意:阿里云数据库连接跟一般数据库连接有所不同


你可能感兴趣的:(MongoDB)