Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of retrying messages by re-queuing
[FunctionName("TopicProcessor")]
public static async Task Run(
[ServiceBusTrigger("%topic-name%", "%subscription-name%", AccessRights.Manage, Connection = "connection")] BrokeredMessage msg,
[ServiceBus("%topic-name%", AccessRights.Manage, Connection = "connection", EntityType = EntityType.Topic)] IAsyncCollector<BrokeredMessage> outputTopic,
ILogger log)
{
var thing = msg.GetBody<Thing>();
try {
var apiClient = new ApiClient();
await apiClient.PostAsync(thing);
// IMPORTANT- Complete the brokered message!
msg.CompleteAsync();
}
catch (BadRequestException) {
await msg.DeadLetterAsync("a-reason-code", "An error description");
}
catch (HttpServiceUnavailableException) {
// we will retry...
await RetryMessageAsync(msg, outputTopic);
}
}
private async Task RetryMessageAsync(BrokeredMessage msg, IAsyncCollector<BrokeredMessage> outputTopic)
{
const string retryCountString = "RetryCount";
// get our custom RetryCount property from the received message if it exists
// if not, initiate it to 0
var retryCount = msg.Properties.ContainsKey(retryCountString)
? (int)msg.Properties[retryCountString]
: 0;
// if we've tried 10 times or more, deadletter this message
if (retryCount >= 10)
{
return _brokeredMessageDeadLetterManager.DeadLetterAsync(msg, "Retry count > 10");
await msg.DeadLetterAsync("too-many-retries", "Retry count > 10");
}
// create a copy of the received message
var clonedMessage = msg.Clone();
// set the ScheduledEnqueueTimeUtc to 30 seconds from now
clonedMessage.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(30);
clonedMessage.Properties[retryCountString] = retryCount + 1;
await outputQueue.AddAsync(clonedMessage);
// IMPORTANT- Complete the original BrokeredMessage!
msg.CompleteAsync();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.