【mq】RabbitMq批量删除队列

  • 【mq】RabbitMq批量删除队列已关闭评论
  • 83 次浏览
  • A+
所属分类:.NET技术
摘要

​ 由于部分公司同事使用RabbitMq时,没有将Client设置为autodelete,导致大量冗余队列。其中这些队列又是无routekey队列,收到了批量的订阅消息,占用服务器内存。


RabbitMq批量删除队列

​ 由于部分公司同事使用RabbitMq时,没有将Client设置为autodelete,导致大量冗余队列。其中这些队列又是无routekey队列,收到了批量的订阅消息,占用服务器内存。

​ 如何将这些无用的队列删除成为一个问题?经过多次摸索,在rabbitmq management api里面找到了方案:

using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json;  class Program {     static async Task Main()     {         string rabbitMQBaseUrl = "https://your_url"; // Replace with your RabbitMQ management interface URL         string vhost = ""; // Replace with the vhost you want to remove queues from         string username = ""; // Replace with your RabbitMQ username         string password = ""; // Replace with your RabbitMQ password          // Get a list of queues in the vhost         var queues = await GetQueuesAsync(rabbitMQBaseUrl, vhost, username, password);          // Delete each queue         foreach (var queue in queues)         {             await DeleteQueueAsync(rabbitMQBaseUrl, vhost, username, password, queue);         }          Console.WriteLine("All queues deleted successfully.");     }      static async Task<string[]> GetQueuesAsync(string baseUrl, string vhost, string username, string password)     {         using (var httpClient = new HttpClient())         {             var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");             httpClient.DefaultRequestHeaders.Authorization =                 new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));              var response = await httpClient.GetStringAsync($"{baseUrl}/api/queues/{Uri.EscapeDataString(vhost)}");              // Parse the JSON response using Newtonsoft.Json             var queueList = JsonConvert.DeserializeObject<QueueInfo[]>(response);              // Extract queue names from the parsed response             var queueNames = queueList.Select(queueInfo => queueInfo.Name).ToArray();              return queueNames;         }     }      static async Task DeleteQueueAsync(string baseUrl, string vhost, string username, string password, string queue)     {         using (var httpClient = new HttpClient())         {             var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");             httpClient.DefaultRequestHeaders.Authorization =                 new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));              await httpClient.DeleteAsync(                 $"{baseUrl}/api/queues/{Uri.EscapeDataString(vhost)}/{Uri.EscapeDataString(queue)}");         }     } }  // Define a class to represent the structure of the QueueInfo received from the API public class QueueInfo {     public string Name { get; set; }     // Add other properties if needed }