Skip to content

Instantly share code, notes, and snippets.

@alexjamesbrown
Created February 23, 2019 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexjamesbrown/4a8c637112583b36b8270dcac71f2600 to your computer and use it in GitHub Desktop.
Save alexjamesbrown/4a8c637112583b36b8270dcac71f2600 to your computer and use it in GitHub Desktop.
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