NoSql之MongoDB的常用类管理(一)

2014-11-24 11:51:58 · 作者: · 浏览: 0
NoSql之MongoDB的常用类管理
1、DBCollection的管理 www.2cto.com
[java]
package com.boonya.mongo;
import java.util.Set;
import com.mongodb.DBCollection;
public class CollectionManager {
public static DBCollection getDbCollection(String collectionName){
return DBConnection.getInstance().getCollection(collectionName.equals("") "myCollection":collectionName);
}
public String getCollectionNames(){
String strNames="";
Set colls =DBConnection.getInstance().getCollectionNames();
for (String cname : colls) {
strNames+=cname+",";
}
return strNames;
}
}
2、并发操作管理
[java]
package com.boonya.mongo;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.WriteConcern;
public class ConcurrencyManager {
private static DBCollection coll= CollectionManager.getDbCollection("myCollection");
/**
* If you want to ensure complete consistency in a “session” (maybe an http request),
* you would want the driver to use the same socket, which you can achieve by using a
* “consistent request”. Call requestStart() before your operations and requestDone()
* to release the connection back to the pool:
* DB and DBCollection are completely thread safe. In fact, they are cached so you get
* the same instance no matter what
*/
public void insertData(){
DB db=DBConnection.getInstance();
db.requestStart();
try {
db.requestEnsureConnection();
//do something
} finally {
db.requestDone();
}
}
/**
* Since by default a connection is given back to the pool after each request, you may
* wonder how calling getLastError() works after a write. You should actually use a
* write concern like WriteConcern.SAFE instead of calling getLastError() manually.
* The driver will then call getLastError() before putting the connection back in the pool.
*
* WriteConcern.NONE No exceptions thrown.
* WriteConcern.NORMAL Exceptions are only thrown when the primary node is unreachable for
* a read, or the full replica set is unreachable.
* WriteConcern.SAFE Same as the above, but exceptions thrown when there is a server error
* on writes or reads. Calls getLastError().
* WriteConcern.REPLICAS_SAFE Tries to write to two separate nodes. Same as the above, but
* will throw an exception if two writes are not possible.
* WriteConcern.FSYNC_SAFE Same as WriteConcern.SAFE, but also waits for write to be written to disk.
*
*/
public void writeConcern(){
coll.insert(new BasicDBObject("name","boonya").append("age", 21), WriteConcern.SAFE);
// is equivalent to
DB db=DBConnection.getInstance();
DBCollection coll=CollectionManager.getDbCollection("myCollection");
db.requestStart();
try {
coll.insert(new BasicDBObject("name","boonya").append("age", 21));
DBObject err = db.getLastError();
System.out.println(err);
} finally {
db.requestDone();
}
}
}
3、 数据库管理
[java]
pac