public class LuceneContext {
/**
* 将该类设置成单例模式,向外只开放轻量级的接口(诸如:IndexSearcher),
* 重量级的变量(诸如:NRTManager、SearcherManager)全部设成私有访问权限.
*/
private static LuceneContext luceneContext;

private static final String PATH = "e:/lucene/index03";
private static Analyzer analyzer;
private static Directory directory;
private static IndexWriter indexWriter;
private static Version version;
private static NRTManager nrtManager;
private static SearcherManager searcherManager;

private LuceneContext(){

}
public static LuceneContext getInstance(){
if (luceneContext == null){
init();
luceneContext = new LuceneContext();
}
return luceneContext;
}

private static void init(){
try {
directory = FSDirectory.open(new File(PATH));
version = Version.LUCENE_35;
analyzer = new MMSegAnalyzer();
indexWriter = new IndexWriter(directory, new IndexWriterConfig(version, analyzer));
nrtManager = new NRTManager(indexWriter, Executors.newCachedThreadPool(), new SearcherWarmer() {
@Override
public void warm(IndexSearcher s) throws IOException {
System.out.println("reopen index");
}
});
searcherManager = nrtManager.getSearcherManager(true);
NRTManagerReopenThread reopenThread = new NRTManagerReopenThread(nrtManager, 5.0, 0.025);
//设置为后台进程,进程退出,该线程就关闭
reopenThread.setDaemon(true);
reopenThread.setName("NRTManagerReopenThread");
reopenThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 获取IndexSearcher
*/
public IndexSearcher getIndexSearcher(){
return searcherManager.acquire();
}

/**
* 释放IndexSearcher
*/
public void releaseIndexSearcher(IndexSearcher indexSearcher){
try {
if (indexSearcher != null){
searcherManager.release(indexSearcher);
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 提交更新后的索引
*/
public void commitIndex(){
try {
indexWriter.commit();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 获取NRTManager(对索引的增删改查需要用到NRTManager)
*/
public NRTManager getNRTManager(){
return nrtManager;
}
}