这个问题还是跟上次的取总数有关,我为了减轻count带来的时间开销,想把count放到一个线程中去执行;
核心代码如下:
/**
* 如果需要返回结果数量,则证明需要总数,此处总数异步查询获取
*/
Thread _myThread = null;
CountThread _Thread = null;
_Thread = new CountThread();
_Thread.setBCollection(_BCollection);
_Thread.setMatcher(_DBQuery.getMatcher());
_myThread = new Thread(_Thread);
_myThread.setName("查询统计数据总数线程");
_myThread.start();
Thread.sleep(100);
/**
* 查询指定条件的游标对象
*/
DBCursor _BCursor = _BCollection.query(_DBQuery);
while (_BCursor.hasNext()) {
BSONObject _value = _BCursor.getNext();
_result.add((T) _value);
}
_BCursor.close();
/**
* 对总数的查询等待结果,并将最终结果赋予setReturnRowsCount(预定)
*/
if (_myThread != null) {
_myThread.join();
if (_Thread != null) {
_DBQuery.setReturnRowsCount(_Thread.getCount());
}
}
getConnection().close(_Sequoiadb);
/**
* 获取总数异步查询
*/
class CountThread implements Runnable {
private DBCollection _BCollection;
private long count;
private BSONObject matcher;
@Override
public void run() {
count = _BCollection.getCount(matcher);
}
/**
* @param _BCollection the _BCollection to set
*/
public void setBCollection(DBCollection _BCollection) {
this._BCollection = _BCollection;
}
/**
* @return the count
*/
public long getCount() {
return count;
}
/**
* @param matcher the matcher to set
*/
public void setMatcher(BSONObject matcher) {
this.matcher = matcher;
}
}
可能是我对线程研究得不够透彻,如果不加入 sleep(1000),则直接抛出异常:
com.sequoiadb.exception.BaseException: errorType:SDB_INVALIDSIZE,Invalid size
Exception Detail:0
at com.sequoiadb.util.SDBMessageHelper.msgExtractReply(SDBMessageHelper.java:623)
at com.sequoiadb.base.DBCollection.adminCommand(DBCollection.java:1647)
at com.sequoiadb.base.DBCollection.query(DBCollection.java:889)
at com.sequoiadb.base.DBCollection.query(DBCollection.java:671)
加入sleep后,经测试会偶然会抛这个异常;
我想问对于多线程,这个API有没有更好的支持的;
另外,项目上用mongodb,也是采用这种方式来取count,这样做完全没问题;