Created
April 28, 2021 22:24
-
-
Save mhagrelius/58c54fd0b7092edbb41f10de9f6420cc to your computer and use it in GitHub Desktop.
Azure Service Bus Dead Letter Queue Drain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>net5.0</TargetFramework> | |
</PropertyGroup> | |
<ItemGroup> | |
<PackageReference Include="Azure.Messaging.ServiceBus" Version="7.1.2"/> | |
<PackageReference Include="CsvHelper" Version="27.0.2"/> | |
</ItemGroup> | |
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Globalization; | |
using System.IO; | |
using Azure.Messaging.ServiceBus; | |
using CsvHelper; | |
string connectionString = @""; | |
string topicName = ""; | |
string subscriptionName = ""; | |
await using var client = new ServiceBusClient(connectionString); | |
var receiver = client.CreateReceiver(topicName, subscriptionName, new ServiceBusReceiverOptions | |
{ | |
SubQueue = SubQueue.DeadLetter, | |
}); | |
List<DeadLetterQueueEntry> entries = new(); | |
ServiceBusReceivedMessage message = null; | |
try | |
{ | |
while (true) | |
{ | |
message = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(5)); | |
if (message == null) | |
{ | |
break; | |
} | |
entries.Add(new DeadLetterQueueEntry(message.DeadLetterReason, message.EnqueuedTime, message.Body.ToString())); | |
await receiver.CompleteMessageAsync(message); | |
Console.WriteLine("Successfully pulled a new message from DLQ."); | |
} | |
} | |
catch | |
{ | |
await receiver.AbandonMessageAsync(message); | |
} | |
finally | |
{ | |
// A safer alternative would be to write each out as received and instead flush here. | |
// See https://joshclose.github.io/CsvHelper/getting-started/ | |
using StreamWriter writer = new("messages.csv"); | |
using CsvWriter csv = new(writer, CultureInfo.InvariantCulture); | |
csv.WriteRecords(entries); | |
} | |
public record DeadLetterQueueEntry(string Reason, DateTimeOffset EqueuedTime, string MessageBody); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment