簡體   English   中英

驗證Web服務中的Solr連接

[英]Authenticate Solr connection in web service

我正在開發一個Web服務,該服務應該獲取一些數據,將其用於查詢,在Solr中搜索並返回適當的結果! 它工作正常,但是到目前為止我只需要初始化一次Solr:

 private static bool initialized = false;

    [WebMethod]
    public XmlDocument getContributor(string name,string email)
    {
        if (!initialized)
        {
            Startup.Init<SolrSearchResult>("http://Host:44416/solr");
            initialized = true;
        }
        if (string.IsNullOrEmpty(email))
        {
            return SolrSearchResult.SearchData(name);
        }
        return SolrSearchResult.SearchDataWithEmail(name, email);
    }

但是我認為,當多個用戶使用時,它將行不通! 我需要一種更聰明的方法來解決這個問題! 我將不勝感激任何建議!

PS:我看過SampleSolrApp,在Application_Start中使用了startup.init,但我不知道在這里等效。

確保可能對getContributor方法進行多個並發調用時,不會多次調用Startup.Init一種方法是引入互斥鎖以同步對該代碼塊的訪問。

在您的情況下,我將首先引入一個靜態對象進行鎖定:

private static readonly object syncRoot = new object();

然后將代碼的那部分用鎖聲明括起來:

lock (syncRoot)
{
    // only 1 thread ever enters here at any time.

    if (!initialized)
    {
        Startup.Init<SolrSearchResult>("http://Host:44416/solr");
        initialized = true;
        // no more threads can ever enter here.
    }
}

lock關鍵字可確保一個線程不會輸入代碼的關鍵部分,而另一個線程位於關鍵部分。 如果另一個線程試圖輸入被鎖定的代碼塊,它將等待直到對象被釋放。

作為旁注; 有一種技巧可用於優化此代碼,進一步稱為雙重檢查鎖定 ,它避免了每次調用getContributor花費很少的性能來獲取鎖定:

// check to see if its worth locking in the first place.
if (!initialized)
{
    lock (syncRoot)
    {
        // only 1 thread ever enters here at any time.

        if (!initialized)
        {
            Startup.Init<SolrSearchResult>("http://Host:44416/solr");
            initialized = true;
            // no more threads can ever enter here.
        }
    }
}

無論出於什么原因, initialized都不需要變為false並且不需要Startup.Init在以后的階段再次運行時,此方法有效。 否則,按原樣使用此代碼可能會遇到問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM