MongoDB 实战笔记 四

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class DBTool {

	private DBTool(){}
	
	private static Mongo w ; //写
	private static Mongo r;    //读
	static{
		if (null == w) {
			synchronized (DBTool.class) {
				try {
					w = new Mongo();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MongoException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		if (null == r) {
			synchronized (DBTool.class) {
				try {
					r = new Mongo("10.166.112.245");
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MongoException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	public static Mongo getWriteDb() {//获取写

		if (null == w) {
			synchronized (w) {
				try {
					w = new Mongo();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MongoException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return w;
	}
	
	public static Mongo getReadDB(){//获取读
		if (null == r) {
			synchronized (r) {
				try {
					r = new Mongo("10.16.112.245");
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MongoException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return r;
	}
		
	public static void colse(){//关闭数据库
		
		if (null != w) {
			w.close();
		}
		if (null != r) {
			r.close();
		}
	}
	
}
import java.util.Iterator;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

public class DBToolOper {

	private Mongo m = null;
	private DB d = null;
	private DBCollection c = null;

	public DBToolOper(String type,String dbName) {//根据传入的类型,开启读写
		if ("w".equals(type)) {
			m = DBTool.getWriteDb();
		} else {
			m = DBTool.getReadDB();
		}
		d = m.getDB(dbName);
	}

	/**
	 * json  {x:1,y:{d:0}}
	 */
	public void writeJson(String json){//把转入的字符串json 转换成json对象
		JSONObject jo = (JSONObject)JSONValue.parse(json);
		Iterator iter = jo.keySet().iterator();
		BasicDBObject doc = new BasicDBObject();
		while (iter.hasNext()) {
			String key = iter.next().toString();
			//System.out.println("[key="+key+", val="+jo.get(key)+"]");
			doc.put(key, jo.get(key));
			
		}
		if (!doc.isEmpty()) {
			c.insert(doc);
		}
		
	}
	
	
	public long getCount(){//获取总数
		return c.getCount();
	}
	public void setDabase(String dbName) {//设置要访问的DB
		d = m.getDB(dbName);
	}
	
	public void setTable(String tbName){//设置要访问的集合
		c = d.getCollection(tbName);
	}
	
	public void printLimit(int row){//获取前row条数据
		DBCursor curr = c.find().limit(row);
		while(curr.hasNext())
			System.out.println(curr.next());
		
	}
	public void printAll(){//打印所有数据
		DBCursor curr = c.find();
		while(curr.hasNext())
			System.out.println(curr.next());
	}
	
	
	public void close(){//关闭数据库
		if (null != m) {
			m.close();
		}
	}
}

测试程序 

 主从数据库 实现读写分离

Random rm = new Random(System.currentTimeMillis());
//读写分离数据库  获取写数据库
DB dw = DBTool.getDB("w");
DBCollection collr = dw.getCollection("c2");
BasicDBObject doc = new BasicDBObject();
doc.put("name"+rm.nextInt(999999999), "MongoDB");
collr.insert(doc);
		
DB dr = DBTool.getDB("r");
collr = dr.getCollection("c2");
DBCursor curr = collr.find().limit(2000);
while(curr.hasNext())
     System.out.println(curr.next());
DBTool.colse();

 登陆具有权限的数据库(用户名,密码)

Mongo m = new Mongo("10.16.112.245");
DB db = m.getDB("mybase");
//获取系统权限 登陆admin 再切换数据库
boolean auth = db.authenticate("root", "888".toCharArray());
db = m.getDB("test");
			
Set<String> colls = db.getCollectionNames();
for (String string : colls) {
      System.out.println(string);
}
			
DBCollection coll = db.getCollection("c2");
System.out.println(coll.count());
DBCursor cur = coll.find().limit(2);
while(cur.hasNext())
     System.out.println(cur.next());
m.close();

 二次封装  ,更方便的操作

DBToolOper dbOper = new DBToolOper("w","mybase");
dbOper.setTable("c8");
for (int i = 0; i < 10; i++) {
     dbOper.writeJson("{\"xx7\":"+i+",\"a\":[{\"b\":0,\"c\":2}]}");
}
System.out.println(dbOper.getCount());
dbOper.printLimit(50);
dbOper.close();

 继续的方向: 条件查询

相关推荐