如果查看在Mongod实例中的lock情况,可以使用如下方式:
1. db.serverStatus
2. db.currentOp
3. mongotop
4. mongostat
5. locks集合

 

MongoDB 在多线程高并发下的问题


com.mongodb.DB 这个类有三个很重要的方法 :

 

public abstract void requestStart() :
starts a new "consistent request". Following this call and until requestDone() is called, all db operations should use the same underlying connection. This is useful to ensure that operations happen in a certain order with predictable results.
public abstract void requestDone():
ends the current "consistent request"

public abstract void requestEnsureConnection():
ensure that a connection is assigned to the current "consistent request" (from primary pool, if connected to a replica set)

具体再查了 MongoDB相关的文档才发现, mongodb 的java driver是不支持是事务性的,所以如果想保证在多线程高并发的情境下不出错(指定的一批数据在同一个底层的数据连接中完成),就必须在使用DB的时候加上上述三个方法。

按照 API 提供的方法说明,在项目代码获得DB的后面加上db.requestStart(),db.requestEnsureConnection(),然后在执行完数据库操作之后加上db.requestDone(),成功解决了数据重复的问题!