如何通过代码从Azure blob存储中删除事件中心分区?

Mik*_*e T 7 azure azure-storage-blobs azure-eventhub

我在C#Winforms项目中使用Azure Event Hubs.

我创建EventProcessorHost和EventReciever对象来执行从事件中心检索消息并显示它们的工作.

我的邮件检索过程的一部分涉及在打开表单时在我的事件中心上创建一个新的使用者组.(我只是将使用者组名称设为新的GUID).

所有这些^都有效.

关闭表单后,将从事件中心删除使用者组,并通过门户网站查看事件中心来验证此情况.

但是,使用者组用于执行Event Hub工作的分区对象仍存在于存储帐户中.

通过CloudBerry资源管理器时,我看到了:

在此输入图像描述

每个GUID是一个消费者组.在我开发的最后几个月里,有数百个,但事件中心一次只能包含20个活跃的消费者群体.

每个使用者组文件夹内有4个文件,其中包含与该使用者组使用的4个分区中的每个分区相关的信息.

事件中心对象(EventReceiver,EventProcessorHost等)上是否有API调用可以自动清除这些对象?我看过,但没有找到任何东西,事件中心的文档目前是最小的.

我查看了EventProcessorHost.PartitionManagerOptions.SkipBlobContainerCreation = true但这没有帮助.

如果没有,是否需要设置存储帐户上的设置以避免垃圾堆积?

谢谢!

Mik*_*e T 2

我最终让它发挥作用。

这实际上只是从存储帐户中删除 blob,但略有不同。

首先,在创建 IEventProcessor 对象时,您需要存储它们的租约信息:

    Task IEventProcessor.OpenAsync(PartitionContext context)
        {
        Singleton.Instance.AddLease(context.Lease);
        Singleton.Instance.ShowUIRunning();
        return Task.FromResult<object>(null);
        }
Run Code Online (Sandbox Code Playgroud)

其中“Singleton”只是我创建的一个单例对象,多个线程可以转储它们的信息。Singleton 的“添加租约”实现:

    public void AddLease(Lease l)
        {
        if (!PartitionIdToLease.ContainsKey(l.PartitionId))
            {
            PartitionIdToLease.Add(l.PartitionId, l.Token);
            }
        else
            PartitionIdToLease[l.PartitionId] = l.Token;
        }
Run Code Online (Sandbox Code Playgroud)

其中“PartitionIdToLease”是

Dictionary<string, string>
Run Code Online (Sandbox Code Playgroud)

现在,删除代码:

CloudStorageAccount acc = CloudStorageAccount.Parse("Your Storage Account Connection String");
CloudBlobClient client = acc.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("Name of Event Hub");
CloudBlobDirectory directory = container.GetDirectoryReference("Name of Folder");


foreach (IListBlobItem item in directory.ListBlobs())
            {
            if (item is CloudBlockBlob)
                {
                CloudBlockBlob cb = item as CloudBlockBlob;
                AccessCondition ac = new AccessCondition();
                string partitionNumber = cb.Name.Substring(cb.Name.IndexOf('/') + 1); //We want the name of the file only, and cb.Name gives us "Folder/Name"

                ac.LeaseId = Singleton.Instance.PartitionIdToLease[partitionNumber];

                cb.ReleaseLease(ac);
                cb.DeleteIfExists();
                }
            }
Run Code Online (Sandbox Code Playgroud)

所以现在每次我的应用程序关闭时,它都会负责删除它在存储帐户中生成的垃圾。

希望这对某人有帮助