用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字

jun    -  云代码空间

—— 相信 ,梦

Lucene 工具类

2014-08-04|1165阅||

摘要:在实际开发中,如果多线程,同时操作索引库, 建立工具类, 提供唯一IndexWriter !


import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**
 * Lucene 工具类
 * 
 * @author seawind
 * 
 */
public class LuceneUtils {
	private static IndexWriter indexWriter;
	private static Directory directory;
	private static Analyzer analyzer = new IKAnalyzer();

	static {
		try {
			IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_36, analyzer);
			directory = FSDirectory.open(new File("index"));
			indexWriter = new IndexWriter(directory, indexWriterConfig);
			Runtime.getRuntime().addShutdownHook(new Thread() {
				@Override
				public void run() {
					try {
						// 关闭索引库
						indexWriter.close();
						System.out.println("索引库 关闭...");
					} catch (CorruptIndexException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 返回IndexWriter
	public static IndexWriter getIndexWriter() {
		return indexWriter;
	}

	// 返回 IndexSearcher
	public static IndexSearcher getIndexSearcher() throws Exception {
		return new IndexSearcher(IndexReader.open(directory));
	}
}

顶 1踩 0收藏
文章评论
    发表评论

    个人资料

    • 昵称: jun
    • 等级: 资深程序员
    • 积分: 1523
    • 代码: 94 个
    • 文章: 24 篇
    • 随想: 0 条
    • 访问: 7 次
    • 关注

    最新提问

      站长推荐