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

最近项目用到 MongoDB , 主要是一些读取数据及改状态位的操作. 因为是结合了最近流行的 Storm进行大数据的分析处理,并将分析结果插入Vertica数据库,所以在多线程高并发的情境下, 会发现 Vertica 数据库中有部分重复的数据. 这到底是什么原因导致的呢?笔者开始也是一筹莫 展,重复去看 MongoDB 的 API , 终于有了新发现 :

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(),成功解决了数据重复的问题!

原创文章,转载请注明出处:

http://bigcat2013.iteye.com/blog/2109233

谢谢!

猜你喜欢

转载自bigcat2013.iteye.com/blog/2109233