Java MongoDB非框架开发进阶--副本集链接开发

最近在用Java做MongoDB的副本集操作开发,由于网上的资料系统性较差,因此,这里进行系统性的记录,供大家参考。

1、MongoDB副本集设置说明

1)在没有进行用户权限设置的情况下进行MongoDB副本集设置,例如:设置副本集rs1

mongod --replSet rs1 --keyFile /home/mongoFile/key/r0 --fork --port 28010 --dbpath /home/mongoFile/data/r0 --logpath=/home/mongoFile/log/r0.log --logappend

mongod --replSet rs1 --keyFile /home/mongoFile/key/r1 --fork --port 28011 --dbpath /home/mongoFile/data/r1 --logpath=/home/mongoFile/log/r1.log --logappend

mongod --replSet rs1 --keyFile /home/mongoFile/key/r2 --fork --port 28012 --dbpath /home/mongoFile/data/r2 --logpath=/home/mongoFile/log/r2.log --logappend

config_rs1 = {_id: 'rs1', members: [{_id: 0, host: '192.168.43.12:28010'},{_id: 1, host: '192.168.43.12:28011'},{_id: 2, host: '192.168.43.12:28012'}]}

rs.initiate(config_rs1)

  2)kill掉所有mongo服务,在各副本中创建数据库,以及权限。例如,要使用admin数据库

mongod --fork --port 28010 --dbpath /home/mongoFile/data/r0 --logpath=/home/mongoFile/log/r0.log --logappend
use admin
db.createUser({user:"admin",pwd:"admin",roles:[{role:"userAdminAnyDatabase",db:"admin"},{role:"clusterAdmin",db:"admin"},{role:"clusterManager",db:"admin"},{role:"readWrite",db:"admin"}]});
mongod --fork --port 28011 --dbpath /home/mongoFile/data/r1 --logpath=/home/mongoFile/log/r1.log --logappend
use admin
db.createUser({user:"admin",pwd:"admin",roles:[{role:"userAdminAnyDatabase",db:"admin"},{role:"clusterAdmin",db:"admin"},{role:"clusterManager",db:"admin"},{role:"readWrite",db:"admin"}]});
mongod --fork --port 28012 --dbpath /home/mongoFile/data/r2 --logpath=/home/mongoFile/log/r2.log --logappend
use admin
db.createUser({user:"admin",pwd:"admin",roles:[{role:"userAdminAnyDatabase",db:"admin"},{role:"clusterAdmin",db:"admin"},{role:"clusterManager",db:"admin"},{role:"readWrite",db:"admin"}]});

  3)现在所有的副本设置操作已经完成,重新启动个副本即可:

mongod --replSet rs1 --keyFile /home/mongoFile/key/r0 --fork --port 28010 --dbpath /home/mongoFile/data/r0 --logpath=/home/mongoFile/log/r0.log --logappend
mongod --replSet rs1 --keyFile /home/mongoFile/key/r1 --fork --port 28011 --dbpath /home/mongoFile/data/r1 --logpath=/home/mongoFile/log/r1.log --logappend
mongod --replSet rs1 --keyFile /home/mongoFile/key/r2 --fork --port 28012 --dbpath /home/mongoFile/data/r2 --logpath=/home/mongoFile/log/r2.log --logappend
2、Java MongoDB副本集操作开发

应用MongoClient链接池即可,示例代码如下:

package Database;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bson.Document;
import Configuration.ConfigCallBack;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBAPI implements DataBaseCallBack{
	public static void main(String[] args) throws InterruptedException{
		System.out.println("start");
		MongoDBAPI m_md = new MongoDBAPI();
		DataBaseParameter m_dp = new DataBaseParameter();
		m_dp.setM_DBname("gps");
		m_dp.setM_IP("192.168.43.4");
		m_dp.setM_Password("liangsheng");
		m_dp.setM_Port(27017);
		m_dp.setM_User("liangsheng");
		m_md.SetInitParameter(m_dp);
		if(m_md.InitDataBase()){
//			DataBaseOperationParameter c_dbop = new DataBaseOperationParameter();
			//插入数据验证
//			c_dbop.setM_TableName("t7070_2016_4_22");
//			c_dbop.setM_Data("aaaaaaaa");
//			c_dbop.setM_Key("PP");
//			c_dbop.setM_Value("ty");
//			m_md.SetOperationParameter(c_dbop);
			//m_md.CreateTable();
//			while(true){
				m_md.Test_InsertData();
//				m_md.QueryDataBase();
//				Thread.sleep(1000);
//			}
		}
		else
			System.out.println("Init error");
	}
	
	//mongodb操作对象
	private MongoClient m_Mongoclient = null;
	private MongoDatabase m_DB = null;
	private MongoCollection m_Collection = null;
	private volatile boolean isCheck = false;
	
	//mongodb操作初始化参数
	private String m_DBname;
	private List m_DBparameters;
	
	@Override
	public boolean InitDataBase(){
		if(null == m_Mongoclient){
			try{
				List c_addrs = new ArrayList();
				List c_credentials = new ArrayList();
				for(int i = 0;i();
		m_DBname = p_dp.getM_DBname();
		m_DBparameters.add(p_dp);
	}
	
	@Override
	public void DestroyDataBase(){
		if(null != m_Mongoclient){
			m_Mongoclient.close();
			m_Mongoclient = null;
			m_DB = null;
			m_Collection = null;
		}
	}
	
	@Override
	public void setAutoCreateInformation(ConfigCallBack p_config){
	}
	
	@Override
	public void AutoCreateTable(){
	}
	
	//判断表格是否存在
	@Override
	public boolean checkTable(String p_name){
		while(true){
			if(!isCheck){
				isCheck = true;
				try{
					if(m_DB.getCollection(p_name).count() > 0)
						break;
					else{
						isCheck = false;
						return false;
					}
				}catch(IllegalArgumentException e){
					isCheck = false;
					return false;
				}
			}
		}
		isCheck = false;
		return true;
	}
	
	//手动创建表格
	@Override
	public boolean CreateTable(String p_name){
		while(true){
			if(!isCheck){
				isCheck = true;
				try{
					m_DB.createCollection(p_name);
				    System.out.println("create collection success");
				    isCheck = false;
				    return true;
				}catch(Exception e){
					e.printStackTrace();
					isCheck =false;
				}
				return false;
			}
		}
	}
	
	public boolean InsertData(Document p_data,String p_tablename){
		if(null == p_data)
			return false;
		try{
			m_Collection = m_DB.getCollection(p_tablename);
			long c_cout = m_Collection.count();
			p_data.append("_id", c_cout+1);
			m_Collection.insertOne(p_data);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		 
		return true;
	}
	
	@Override
	public boolean beginToDeal(BASEOPERATION p_operation, Object p_data, String p_tablename) {
		// TODO Auto-generated method stub
		if(null == p_operation || null == p_data)
			return false;
		
		if(p_data instanceof Document){
			Document c_data = (Document) p_data;
			switch(p_operation){
			case insert:
				if(InsertData(c_data, p_tablename))
					break;
				else
					return false;
			case query:
				break;
				default:
					return false;
			}
		}
		return true;
	}
	
	//测试查询数据库
	@SuppressWarnings("deprecation")
	public boolean QueryDataBase(){
		try{
			m_Collection = null;
//			m_Collection = m_DB.getCollection("Vehicle7070_2016_4_22");
			m_Collection = m_DB.getCollection("vehile集合");
            System.out.println("集合 test 选择成功");
            
            
            
            //检索所有文档  
            /** 
            * 1. 获取迭代器FindIterable 
            * 2. 获取游标MongoCursor 
            * 3. 通过游标遍历检索出的文档集合 
            * */  
            BasicDBObject query = new BasicDBObject();
            query.put("TIME", BasicDBObjectBuilder.start("$gte",new Date(2016-1900,4-1,22,0,0,0)).add("$lte", new Date(2016-1900,4-1,22,23,59,0)).get());
            
            BasicDBObject queryf = new BasicDBObject();
            queryf.put("TIME", -1);
            
            
            FindIterable c_findIterable = m_Collection.find(new Document("PP","ty")).sort(queryf);
//            FindIterable c_findIterable = m_Collection.find(query);
            MongoCursor c_mongoCursor = c_findIterable.iterator();  
            while(c_mongoCursor.hasNext()){  
               System.out.println(c_mongoCursor.next());  
            }  
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	//测试插入语句
	public boolean Test_InsertData(){
		try{
//			m_Collection = m_DB.getCollection(m_DBOP.getM_TableName());
			m_Collection = m_DB.getCollection("粤B 666888_2017_09_06");
            System.out.println("集合 test 选择成功");
            
            //IsoChronology
            //插入文档  
            /** 
            * 1. 创建文档 org.bson.Document 参数为key-value的格式 
            * 2. 创建文档集合List 
            * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List) 插入单个文档可以用 mongoCollection.insertOne(Document) 
            * */
            
            double d_lanti_n = 3644.5000;
            double d_longi_n = 00930.5000;
            
            for(int i = 0;i<20000;i++){
	            Document dddd = new Document();
	            dddd.append("TIME", new Date());
	            dddd.append("LATI", "N");
	            dddd.append("LONGI", "E");
//	            double d_lanti_n = 3644.5000 + new Random().nextDouble()*(3650.0000-3644.5000);
	            d_lanti_n = d_lanti_n + 0.0009;
	            dddd.append("LATI_N", new DecimalFormat("0000.0000").format(d_lanti_n));
//	            double d_longi_n = 00930.5000 + new Random().nextDouble()*(00940.5000-00930.5000);
	            d_longi_n = d_longi_n + 0.001;
	            dddd.append("LONGI_N", new DecimalFormat("00000.0000").format(d_longi_n));
	            long c_cout = m_Collection.count();
	            dddd.append("_id", c_cout+1);
	            System.out.println(c_cout);
	            m_Collection.insertOne(dddd);  
	            System.out.println("文档插入成功");
	            Thread.sleep(1000);
            }
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	//测试建表
	public boolean CreateTable(){
		try{
			m_DB.createCollection("vehile集合");
		    System.out.println("集合创建成功");
		    return true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	//测试变量
//	private DataBaseOperationParameter m_DBOP;
	
	//测试使用
//	public void SetOperationParameter(DataBaseOperationParameter p_dbop){
//		m_DBOP = p_dbop;
//	}
	
}

你可能感兴趣的:(Java)