[英]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.