SolrCloud-如何在.NET程式中使用

來源:互聯網
上載者:User

標籤:

https://github.com/vladen/SolrNet

 

原來我們在我們的項目裡用的是根據資料庫路由到不同的單機Solr伺服器,但是這樣的話,每次Solr配置的修改都要修改三台不通的伺服器,而且一台伺服器掛了,必定會影響一部分使用者不能使用搜尋功能,而且還會造成一定程度的丟資料,所以我們換一種方式。

兩種可選方案:

  • 主從模式
  • SolrCloud

經過對比,決定用SolrCloud,SolrCloud的概念和優缺點,就不再贅述了,網上一搜一大堆,這裡主要寫一下在C#如何使用SolrCloud。

最早我們用 EasyNet.Solr 來進行Solr查詢的,但是貌似EasyNet.Solr 沒有對SolrCloud的查詢做封裝,所以就各種找資料,最後只能自己封裝了。

首先SolrCloud是通過zookeeper來調度的,那麼我們就要先去zookeeper上面去load可用的節點,並且對 zookeeper的 clusterstate.json 檔案做心跳檢測,如果clusterstate.json 裡的內容有變化,則說明節點狀態有變化,需要重新load檔案裡的內容進行解析,否則就在應用程式第一次調用的時候載入一次,緩衝起來。

獻上核心代碼

要先通過NuGet安裝Zookeeper Client

在EasyNet.Solr根目錄定義介面ISolrCloudOperrations.cs

using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;namespace EasyNet.Solr  {    public interface ISolrCloudOperrations { string GetSolrCloudServer(string collectionName, bool isWrite); }}

在Impl檔案夾裡實現介面 SolrCloudOperations.cs

internal static class ZookeeperStatus      {        //每隔兩秒鐘pingzookeeper伺服器,並監聽solr伺服器狀態,如果狀態有改變,更新狀態檔案,請求串連列表        private static void Ping(string zkHost) { //如果是第一次調用,則載入設定檔 if (DataLength == 0) { foreach (var host in zkHost.Split(‘,‘).ToList()) { Start(host); } Task.Factory.StartNew(() => { while (true) { foreach (var host in zkHost.Split(‘,‘).ToList()) { Task.Factory.StartNew(Start, host); } Thread.Sleep(2000); } }); } } private static object pingObj = new object(); private static void Start(object zkHost) { var watcher = new Watcher(); using (var zk = new ZooKeeper(zkHost.ToString(), new TimeSpan(0, 0, 0, 10000), watcher)) { var dataChange = watcher.WaitUntilWatched(); Org.Apache.Zookeeper.Data.Stat stat = null; try { stat = zk.Exists("/clusterstate.json", false); } finally { if (stat != null) { byte[] data = null; lock (pingObj) { if (DataLength == 0 || DataLength != stat.DataLength) { data = zk.GetData("/clusterstate.json", false, stat); DataLength = stat.DataLength; SetShard(data); } } } } } } private static int DataLength = 0; private static Dictionary<string, List<Shard>> shards = new Dictionary<string, System.Collections.Generic.List<Shard>>(); private static ReaderWriterLockSlim rw = new ReaderWriterLockSlim(); private static void SetShard(byte[] data) { var str = System.Text.Encoding.UTF8.GetString(data); JObject jObj = JsonConvert.DeserializeObject<JObject>(str); List<Shard> shardList = new List<Shard>(); try { rw.EnterWriteLock(); foreach (var p in jObj) { foreach (var item in p.Value["shards"]) { var jItem = item.First as JObject; if (jItem["state"].ToString() == "active") { foreach (var replica in jItem["replicas"]) { var jReplica = replica.First as JObject; if (jReplica["state"].ToString() == "active") { Shard shard = new Shard() { BaseUrl = jReplica["base_url"].ToString() }; if (jReplica["leader"] != null && "true" == jReplica["leader"].ToString()) { shard.Leader = true; } shardList.Add(shard); } } } } if (shards.ContainsKey(p.Key)) { shards[p.Key] = shardList; } else { shards.Add(p.Key, shardList); } } } finally { rw.ExitWriteLock(); } } public static string ZookeeperHost = "127.0.0.1:2181"; public static string GetCollection(string collectionName, bool isWrite) { ///第一次調用,則開始ping if (DataLength == 0) { Ping(ZookeeperHost); } IEnumerable<Shard> tempShardList = null; try { rw.EnterReadLock(); var shardList = shards[collectionName]; if (!isWrite) { tempShardList = shardList.Where(s => s.Leader == false); } //如果從庫掛了,那麼只能從主庫讀取了 if (tempShardList == null || tempShardList.Count() == 0) tempShardList = shardList.Where(s => s.Leader == true); } finally { rw.ExitReadLock(); } if (tempShardList == null) throw new Exception("no active shard"); //隨機取值 int random = new Random().Next(tempShardList.Count() - 1); return tempShardList.ToList()[random].BaseUrl; } } internal class Shard { public string BaseUrl { get; set; } public bool Leader { get; set; } } internal enum Changed { None, Children, Data } internal class Watcher : IWatcher { private readonly ManualResetEventSlim _changed = new ManualResetEventSlim(false); private WatchedEvent _event; public Changed WaitUntilWatched() { _changed.Wait(); if (_event == null) throw new ApplicationException("bad state"); if (_event.State != KeeperState.SyncConnected) throw new ApplicationException("cannot connect"); if (_event.Type == EventType.NodeChildrenChanged) { return Changed.Children; } if (_event.Type == EventType.NodeDataChanged) { return Changed.Data; } return Changed.None; } void IWatcher.Process(WatchedEvent @event) { _event = @event; _changed.Set(); } }

這樣我們如果是write操作,就會調用leader分區對應的節點進行寫入,如果是查詢操作,則盡量直接調用非leader來進行查詢,如果非leader節點掛了,那麼久從主節點進行查詢。

SolrCloud-如何在.NET程式中使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.