标签:Lucene style class blog code java
在Hibernate中,一般保持一个数据库就只有一个SessionFactory。因为在SessionFactory中维护二级缓存,而SessionFactory又是线程安全的。所以SessionFactory是共享的。
如果同时在一个索引库中同时建立两个IndexWriter,例如:
IndexWriter indexWriter = new IndexWriter(LuceneUtils.directory,LuceneUtils.analyzer,MaxFieldLength.LIMITED); IndexWriter indexWriter2 = new IndexWriter(LuceneUtils.directory,LuceneUtils.analyzer,MaxFieldLength.LIMITED);
结论:同一个索引库只能有一个IndexWriter进行操作。
public class LuceneIndexWriter {
private static IndexWriter indexWriter = null;
public static IndexWriter getIndexWriter() {
if (indexWriter == null) {
try {
indexWriter = new IndexWriter(LuceneUtils.directory,
LuceneUtils.analyzer, MaxFieldLength.LIMITED);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (LockObtainFailedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return indexWriter;
}
public static void close() {
if (indexWriter != null) {
try {
indexWriter.close();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("indexWriter为空,不能关闭!");
}
}
}
注:这里用单例模式做比较好。/**
* 1、索引库的增、删、改是由indexWriter来操作的
* 2、同一个时刻内,同一个索引库,只能允许一个indexWriter操作
* 3、当IndexWriter创建完成以后,indexwriter所指向的索引库就被占领了,只有当indexWriter.close时,才能释放锁的资源
* 4、当一个新的indexWriter想拥有索引库时,原来的indexWriter必须释放锁
* 5、只要索引库中存在write.lock文件,说明上锁了
* 6、indexWriter.close有两层含义:
* * 关闭IO资源
* * 释放锁
* @author Administrator
*
*/
public class IndexWriterTest {
@Test
public void testIndexWriter() throws Exception{
IndexWriter indexWriter = new IndexWriter(LuceneUtils.directory,LuceneUtils.analyzer,MaxFieldLength.LIMITED);
indexWriter.close();
IndexWriter indexWriter2 = new IndexWriter(LuceneUtils.directory,LuceneUtils.analyzer,MaxFieldLength.LIMITED);
}
}
在执行完上述代码后,索引库的结构为:
lucene_indexWriter说明、索引库优化,布布扣,bubuko.com
标签:Lucene style class blog code java
原文地址:http://blog.csdn.net/jerome_s/article/details/33766551