【问题标题】:Thread safe writing to Lucene index files线程安全写入 Lucene 索引文件
【发布时间】:2012-02-22 04:58:53
【问题描述】:

我有一个应用程序可以爬取网站并将内容作为 lucene 索引文件写入物理目录。

当我为此目的使用线程时,由于锁定,我会遇到写入错误或错误。

我想使用多个线程并写入索引文件而不会丢失任何线程的任务。

public class WriteDocument
{
    private static Analyzer _analyzer;

    private static IndexWriter indexWriter;

    private static string Host;

    public WriteDocument(string _Host)
    {
        Host = _Host;
        Lucene.Net.Store.Directory _directory = FSDirectory.GetDirectory(Host, false);
        _analyzer = new StandardAnalyzer();
        bool indexExists = IndexReader.IndexExists(_directory);
        bool createIndex = !indexExists;

        indexWriter = new IndexWriter(_directory, _analyzer, true);
    }
    public void AddDocument(object obj)
    {
           DocumentSettings doc = (DocumentSettings)obj;               
           Field urlField = new Field("Url", doc.downloadedDocument.Uri.ToString(), Field.Store.YES, Field.Index.TOKENIZED);
            document.Add(urlField);
            indexWriter.AddDocument(document);

            document = null;
            doc.downloadedDocument = null;

            indexWriter.Optimize();
            indexWriter.Close();
      }
}

对于上面的类,我传递的值是这样的:

DocumentSettings writedoc = new DocumentSettings()
{
      Host = Host,
      downloadedDocument = downloadDocument
};
Thread t = new Thread(() =>
{
doc.AddDocument(writedoc);
});
t.Start();

如果我在t.Start(); 之后添加t.Join();,则代码对我有效,没有任何错误。但这会减慢我的进程,实际上,这等于我在不使用线程的情况下得到的输出。

我收到如下错误:

Cannot rename /indexes/Segments.new to /indexes/Segments 
the file is used by some other process.

谁能帮我解决这个代码?

【问题讨论】:

  • 您遇到什么错误?我们可以看看你正在使用的代码的一个小例子吗?

标签: c# multithreading thread-safety threadpool web-crawler


【解决方案1】:

IndexWriter 不是线程安全的,所以这是不可能的。

如果您想使用多个线程进行下载,则需要构建某种单线程“消息泵”,您可以将正在下载和创建的文档提供给该“消息泵”,并将它们放入队列中。

例如,在您的 AddDocument 方法中,不要直接使用索引,而是将它们发送到最终将索引它的服务。

该服务应该一直尝试索引队列中的所有内容,如果它暂时没有队列,则休眠一段时间。

【讨论】:

  • 好吧,我很困惑 - Lucene.net 3.0.3 文档说 IndexWriter 是 thread-safe
【解决方案2】:

您可以采取的一种方法是为每个线程创建一个单独的索引,并在最后将它们全部合并。例如index1, index2...indexn(对应线程1..n)并合并它们。

【讨论】:

    猜你喜欢
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多