【问题标题】:Creating an Azure ServiceBus Queue via code通过代码创建 Azure ServiceBus 队列
【发布时间】:2019-09-03 03:39:03
【问题描述】:

抱歉,我是 Azure 的新手。我使用 tutorial 通过 Azure 门户创建了一个服务总线和队列。

我可以从队列中读写。问题是,要部署到下一个环境,我必须更新 ARM 模板以添加新队列或在代码中创建队列。在下一个环境中无法通过门户创建队列。

我选择了后者:检查队列是否存在并根据需要通过代码创建。我已经为 CloudQueueClient (在 Microsoft.WindowsAzure.Storage.Queue 命名空间中)提供了一个实现。这将使用 CloudStorageAccount 实体来创建 CloudQueueClient(如果它不存在)。

我希望它会这么简单,但似乎并非如此。我正在努力寻找一种方法来创建QueueClint(在 Microsoft.Azure.ServiceBus 命名空间中)。我所拥有的只是服务总线连接字符串和队列名称,但在搜索了 Microsoft 文档后,有人谈到了该过程中涉及的 NamespaceManagerMessagingFactory(在不同的命名空间中)。

谁能指出我如何实现这一目标,更重要的是,这是正确的方法吗?我将使用 DI 来实例化队列,因此检查/创建只会进行一次。

服务总线队列而不是存储帐户队列需要该解决方案。差异概述here

谢谢

【问题讨论】:

    标签: c# azure .net-core asp.net-core-2.0 azure-servicebus-queues


    【解决方案1】:

    Sean Feldman 的回答为我指明了正确的方向。所需的主要 nuget 包/命名空间(.net core)是

    • Microsoft.Azure.ServiceBus
    • Microsoft.Azure.ServiceBus.Management

      这是我的解决方案:

      private readonly Lazy<Task<QueueClient>> asyncClient; private readonly QueueClient client;

      public MessageBusService(string connectionString, string queueName)
      {
          asyncClient = new Lazy<Task<QueueClient>>(async () =>
          {
              var managementClient = new ManagementClient(connectionString);
      
              var allQueues = await managementClient.GetQueuesAsync();
      
              var foundQueue = allQueues.Where(q => q.Path == queueName.ToLower()).SingleOrDefault();
      
              if (foundQueue == null)
              {
                  await managementClient.CreateQueueAsync(queueName);//add queue desciption properties
              }
      
      
              return new QueueClient(connectionString, queueName);
          });
      
          client = asyncClient.Value.Result; 
      }
      

    不是最容易找到的东西,但希望它可以帮助某人。

    【讨论】:

    • 伙计,这救了我的命。非常感谢。我什至不知道你在哪里找到这个代码
    【解决方案2】:

    要使用新客户端 Microsoft.Azure.ServiceBus 创建实体,您需要通过创建实例并调用 CreateQueueAsync() 来使用 ManagemnetClient

    【讨论】:

      【解决方案3】:

      您同样可以使用 NamespaceManager 创建服务总线队列,

      QueueDescription _serviceBusQueue = new QueueDescription("QUEUENAME");   //assign the required properties to _serviceBusQueue 
      
      NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString("CONNECTIONSTRING");
      
      var queue = await namespaceManager.CreateQueueAsync(_azureQueue);
      

      【讨论】:

      • 谢谢,但 NameSpaceManager 在面向 .net 核心的 Azure ServiceBus Nuget 包中不可用。我需要使用 Azure 资源管理器来创建这些实体。你的回答让我走上了这条路:tomasherceg.com/blog/post/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多