lucene,如何将SearcherManager和SearcherLifetimeManager一起使用

时间:2015-09-01 17:13:46

标签: java solr elasticsearch lucene

在lucene文档中的SearcherManager

            IndexSearcher s = manager.acquire();
            try {
              // Do searching, doc retrieval, etc. with s
            } finally {
                manager.release(s);
            }
            // Do not use s after this!
            s = null;

因此,搜索后应该释放对象而不再使用它。 但是SearcherLifetimeManager需要在内部Map中存储indexsearcher,然后得到它:

           long token = mgr.record(searcher);
           IndexSearcher searcher = mgr.acquire(token);
           mgr.release(searcher);

如何将这两种方法结合使用而不是破坏 订购API调用?

1 个答案:

答案 0 :(得分:3)

基本上,您需要来自用户的令牌并检查,如果此令牌对LifetimeManager仍然有效,否则您使用SearcherManager中的新IndexSearcher创建新令牌。它看起来像这样:

// Boxed Long, can be null to mean that you might not have a token.
// You could also use Optional or something similar.
Long tokenFromRequest;

// Might be the same as the incoming token or a new one.
Long tokenToReturn;

IndexSearcher is;
if (tokenFromRequest == null) { // no previous token, need a new one
  is = manager.acquire(); // get searcher from SearcherManager
  tokenToReturn = mgr.record(is); // get a fresh token for this searcher
} else {
  is = mgr.acquire(tokenFromRequest); // try to get the recorded searcher
  if (is != null) { // token is valid
    tokenToReturn = tokenFromRequest;
  } else {
    is = manager.acquire(); // get searcher from SearcherManager
    tokenToReturn = mgr.record(is); // get a token for this searcher
  }
}

try {
  // Do searching, doc retrieval, etc. with is
} finally {
  if (tokenToReturn == tokenFromRequest) {
    // token was valid, we need to release the searcher
    // to the LifetimeManager, the SearcherManager had
    // nothing to do with this IndexSearcher
    mgr.release(is);
  } else {
    // we got this searcher from SearcherManager,
    // the LifetimeManager records its usage as well and
    // we need to release it to show that _we_ are finished
    // using it, otherwise it would be kept open forever
    manager.release(is);
  }

}
// Do not use is after this!
is = null;

//return tokenToReturn to user to be sent with the next request