我正在ASP.net MVC 4中向Solr写一个前端,我想连接到Zookeeper并读取活动节点并连接到一个随机节点。为此,我写了这段代码:
public class zkResolver
{
private static readonly TimeSpan timeout = TimeSpan.FromSeconds(400);
private const String LIVE_NODES_ZKNODE = "/live_nodes";
public String ErrorMsg { get; set; }
public static String getActiveInstance(String instanceUrl)
{
ZooKeeper zk = new ZooKeeper(instanceUrl, timeout, null);
List<String> activeNodes = zk.GetChildren(LIVE_NODES_ZKNODE, false);
Random rnd = new Random();
int i = rnd.Next(0, activeNodes.Count - 1); //lets shuffle baby
return activeNodes[i];
}
}
然而,当我运行它时它返回-4(CONNECTIONLOSS),但是当我开始调试时,它会返回正确的结果,任何想法,为什么???
答案 0 :(得分:2)
好的,我已经解决了这个问题。 ZooKeeper在ctor中有异步连接,所以你必须等到它与smth连接如下:
while (zk.State == ZooKeeperNet.ZooKeeper.States.CONNECTING)
{
Thread.Sleep(TimeSpan.FromSeconds(1));
}