簡體   English   中英

發生錯誤后如何保持頻道正常運行?

[英]How can I keep a Channel alive after an error?

我想刪除RabbitMQ服務器上的幾個隊列,並提供一些類似於以下代碼的代碼:

string[] queuesToDelete = new[] {
  "QueueThatExists1",
  "QueueThatDoesn'tExist", // this queue causes an error - which I expect
  "QueueThatExists2" };    // this queue also errors - which I don't expect

IConnectionFactory factory = ...
using (IModel = factory.CreateModel()) {
  foreach (string queue in queuesToDelete) {
    try {
      model.QueueDelete(queue);
      Console.WriteLine("Queue {0} deleted");
    } catch (Exception e) {
      Console.WriteLine("Queue {0} could not be deleted because {1}", queue, e);
    }
  }
}

但是我得到這個作為輸出:

隊列QueueThatExists1已刪除
由於未找到隊列,無法刪除隊列QueueThatDoesn'tExist
無法刪除隊列QueueThatExists2,因為已經關閉

我已經更改了代碼,使其看起來更像這樣(按我的預期工作):

string[] queuesToDelete = new[] {
  "QueueThatExists1",
  "QueueThatDoesn'tExist", // this queue causes an error - which I expect
  "QueueThatExists2" };    // this queue also errors - which I don't expect

IConnectionFactory factory = ...
IModel model;
try {
  model = factory.CreateModel();
  foreach (string queue in queuesToDelete) {
    try {
      model.QueueDelete(queue);
      Console.WriteLine("Queue {0} deleted");
    } catch (Exception e) {
      Console.WriteLine("Queue {0} could not be deleted because {1}", queue, e);
      // reset the connection
      model.Dispose();
      model = factory.CreateModel();
    }
  } finally {
    if (model != null)
      model.Dispose();
  }
}

但是,這看起來很糟糕。 我已經刪除了一條using語句,並try - finally了相同的try - finally阻止。 感覺就像我在打API。 問題:是否有更優雅的方法來達到相同的結果?

我注意到Java的RabbitMQ具有lyraautorecovery ,但是找不到與C#類似的東西。

出項目EasyNetQ

EasyNetQ實現訂戶重新連接( EasyNetQ doc )。

我建議您檢查一下是否存在,而不是嘗試/捕獲。 您可以使用API​​進行此操作。 這是我們的方法:

  private bool DoesSomethingExist(string something, string queueOrExchange)
    {
        var connectionInfo = GetRabbitConnectionInfo();
        var url = string.Format("{0}/{1}/{2}/{3}", connectionInfo.APIUrl, queueOrExchange, connectionInfo.VirtualHostName, something);
        using (var client = new HttpClient())
        {
            var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", connectionInfo.UserName, connectionInfo.Password));
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            var response = client.GetAsync(url).Result;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return true;
            }
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return false;
            }

            var content = response.Content;
            throw new Exception(string.Format("Unhandled API response code of {0}, content: {1}", response.StatusCode, content));
        }
    }

暫無
暫無

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

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