public async Task DequeueAndUpdateAsync() { // Get a connection string to our Azure Storage account. string connectionString = ConnectionString; // Get a reference to a queue named "sample-queue" and then create it QueueClient queue = new QueueClient(connectionString, Randomize("sample-queue")); await queue.CreateAsync(); try { // Add several messages to the queue await queue.SendMessageAsync("first"); await queue.SendMessageAsync("second"); await queue.SendMessageAsync("third"); // Get the messages from the queue with a short visibility timeout List <QueueMessage> messages = new List <QueueMessage>(); foreach (QueueMessage message in (await queue.ReceiveMessagesAsync(10, TimeSpan.FromSeconds(1))).Value) { // Tell the service we need a little more time to process the message UpdateReceipt changedMessage = await queue.UpdateMessageAsync( message.MessageId, message.PopReceipt, message.MessageText, TimeSpan.FromSeconds(5)); messages.Add(message.Update(changedMessage)); } // Wait until the visibility window times out await Task.Delay(TimeSpan.FromSeconds(1.5)); // Ensure the messages aren't visible yet Assert.AreEqual(0, (await queue.ReceiveMessagesAsync(10)).Value.Count()); // Finish processing the messages foreach (QueueMessage message in messages) { // Tell the service we need a little more time to process the message await queue.DeleteMessageAsync(message.MessageId, message.PopReceipt); } } finally { // Clean up after the test when we're finished await queue.DeleteAsync(); } }
/// <summary> /// Receive messages and update their visibility timeout for extended /// processing. /// </summary> /// <param name="connectionString"> /// A connection string to your Azure Storage account. /// </param> /// <param name="queueName"> /// The name of an existing queue to operate on. /// </param> public static async Task ReceiveAndUpdateAsync(string connectionString, string queueName) { // Get a reference to a queue and then fill it with messages QueueClient queue = new QueueClient(connectionString, queueName); await queue.SendMessageAsync("first"); await queue.SendMessageAsync("second"); await queue.SendMessageAsync("third"); // Get the messages from the queue with a short visibility timeout // of 1 second List <QueueMessage> messages = new List <QueueMessage>(); Response <QueueMessage[]> received = await queue.ReceiveMessagesAsync(10, TimeSpan.FromSeconds(1)); foreach (QueueMessage message in received.Value) { // Tell the service we need a little more time to process the // message by giving them a 5 second visiblity window UpdateReceipt receipt = await queue.UpdateMessageAsync( message.MessageId, message.PopReceipt, message.MessageText, TimeSpan.FromSeconds(5)); // Keep track of the updated messages messages.Add(message.Update(receipt)); } // Wait until the original 1 second visiblity window times out and // check to make sure the messages aren't showing up yet await Task.Delay(TimeSpan.FromSeconds(1.5)); Assert.AreEqual(0, (await queue.ReceiveMessagesAsync(10)).Value.Length); // Finish processing the messages foreach (QueueMessage message in messages) { // "Process" the message Console.WriteLine($"Message: {message.MessageText}"); // Tell the service we need a little more time to process the message await queue.DeleteMessageAsync(message.MessageId, message.PopReceipt); } }
public IActionResult UpdateReceipt([FromBody] JObject data) { var LoginUserIdentifier = ""; try { //gets the login token from Auth0 LoginUserIdentifier = User.FindFirst(ClaimTypes.NameIdentifier).Value; } catch (Exception e) { LoginUserIdentifier = ""; } var connStr = _config["ConnectionStrings:DefaultConnection"]; UpdateReceipt updatereceipt = data["receipt"].ToObject <UpdateReceipt>(); using (IDbConnection db = new SqlConnection(connStr)) { var SqlStr = @"Update receipts set Date = @Date, Store = @Store, Tax = @Tax, TotalAmount = @TotalAmount where id = @ID and Auth0ID = @LoginUserIdentifier"; var result = db.Execute(SqlStr, new { Date = updatereceipt.date, Store = updatereceipt.store, Tax = updatereceipt.tax, TotalAmount = updatereceipt.totalAmount, ID = updatereceipt.id, LoginUserIdentifier = LoginUserIdentifier } ); } return(Ok(updatereceipt)); }
/// <summary> /// Continually renew the message lease while processing is occuring in another task. /// </summary> /// <returns>the current pop receipt (optimistic concurrency control) for the message.</returns> private async Task <string> RenewMessageLeaseAsync(QueueClient queueClient, QueueMessage message, CancellationToken cancellationToken) { var leasePeriod = this.options.CurrentValue.MessageLeasePeriod; var halfLife = new TimeSpan(leasePeriod.Ticks / 2); var queueName = queueClient.Name; var messageId = message.MessageId; var popReceipt = message.PopReceipt; var nextVisibleOn = message.NextVisibleOn; try { while (true) { // We extend the lease after half of the lease period has expired. // For a 30 second MessageLeasePeriod, every 15 seconds, we'll set the message to invisible // for 30 seconds. await Task.Delay(halfLife, cancellationToken); this.logger.LogDebug("Extending visibility timeout for message.\n Queue: {Queue}\n Message: {MessageId}\n Pop Receipt: {PopReceipt}\n Visible in: {VisibleIn}", queueName, messageId, popReceipt, nextVisibleOn - DateTimeOffset.UtcNow); UpdateReceipt receipt = await queueClient.UpdateMessageAsync(messageId, popReceipt, visibilityTimeout : leasePeriod, cancellationToken : cancellationToken); var oldPopReceipt = popReceipt; popReceipt = receipt.PopReceipt; nextVisibleOn = receipt.NextVisibleOn; this.logger.LogDebug("Message visibility extended. Queue: {Queue}\n Message: {MessageId}\n Old pop receipt: {OldPopReceipt}\n New pop receipt: {NewPopReceipt}\n Visible in: {VisibleIn}", queueName, messageId, oldPopReceipt, popReceipt, nextVisibleOn - DateTimeOffset.UtcNow); } } catch (OperationCanceledException) when(cancellationToken.IsCancellationRequested) { // It's normal for RenewMassageAsync to be cancelled when ProcessMessageAsync completes. // Log the cancellation and return success this.logger.LogDebug("RenewMessageAsync received a cancellation request. Message: {MessageId}\n Pop Receipt: {PopReceipt}", messageId, popReceipt); } catch (Exception ex) { // It's not normal for RenewMassageAsync to throw any exception other than OperationCanceledException. // Log the exception and rethrow this.logger.LogError(ex, "Unexpected exception when trying to renew message lease. Queue: {Queue}\n Message: {MessageId}\n Pop Receipt: {PopReceipt}", queueName, messageId, popReceipt); throw; } return(popReceipt); }
public async Task <TaskSeriesCommandResult> ExecuteAsync(CancellationToken cancellationToken) { TimeSpan delay; try { UpdateReceipt updateReceipt = await _queue.UpdateMessageAsync(_message.MessageId, _message.PopReceipt, visibilityTimeout : _visibilityTimeout, cancellationToken : cancellationToken).ConfigureAwait(false); _message = _message.Update(updateReceipt); _onUpdateReceipt?.Invoke(updateReceipt); // The next execution should occur after a normal delay. delay = _speedupStrategy.GetNextDelay(executionSucceeded: true); } catch (RequestFailedException exception) { // For consistency, the exceptions handled here should match PollQueueCommand.DeleteMessageAsync. if (exception.IsServerSideError()) { // The next execution should occur more quickly (try to update the visibility before it expires). delay = _speedupStrategy.GetNextDelay(executionSucceeded: false); } if (exception.IsBadRequestPopReceiptMismatch()) { // There's no point to executing again. Once the pop receipt doesn't match, we've permanently lost // ownership. delay = Timeout.InfiniteTimeSpan; } else if (exception.IsNotFoundMessageOrQueueNotFound() || exception.IsConflictQueueBeingDeletedOrDisabled()) { // There's no point to executing again. Once the message or queue is deleted, we've permanently lost // ownership. // For queue disabled, in theory it's possible the queue could be re-enabled, but the scenarios here // are currently unclear. delay = Timeout.InfiniteTimeSpan; } else { throw; } } return(new TaskSeriesCommandResult(wait: Task.Delay(delay, cancellationToken))); }
/// <summary> /// Receive messages and update their visibility timeout for extended /// processing. /// </summary> /// <param name="connectionString"> /// A connection string to your Azure Storage account. /// </param> /// <param name="queueName"> /// The name of an existing queue to operate on. /// </param> public static void ReceiveAndUpdate(string connectionString, string queueName) { // Add several messages to the queue QueueClient queue = new QueueClient(connectionString, queueName); queue.SendMessage("first"); queue.SendMessage("second"); queue.SendMessage("third"); // Get the messages from the queue with a short visibility timeout // of 1 second List <QueueMessage> messages = new List <QueueMessage>(); foreach (QueueMessage message in queue.ReceiveMessages(10, TimeSpan.FromSeconds(1)).Value) { // Tell the service we need a little more time to process the // message by giving them a 5 second visiblity window UpdateReceipt receipt = queue.UpdateMessage( message.MessageId, message.PopReceipt, message.MessageText, TimeSpan.FromSeconds(5)); // Keep track of the updated messages messages.Add(message.Update(receipt)); } // Wait until the original 1 second visiblity window times out and // check to make sure the messages aren't showing up yet Thread.Sleep(TimeSpan.FromSeconds(1.5)); Assert.AreEqual(0, queue.ReceiveMessages(10).Value.Length); // Finish processing the messages foreach (QueueMessage message in messages) { // "Process" the message Console.WriteLine($"Message: {message.MessageText}"); // Tell the service we need a little more time to process the message queue.DeleteMessage(message.MessageId, message.PopReceipt); } }
static async Task ReceiveAndUpdateAsync(string connectionString, string queueName) { QueueClient queue = new QueueClient(connectionString, queueName); await queue.SendMessageAsync("first"); await queue.SendMessageAsync("second"); await queue.SendMessageAsync("third"); // получаем сообщения из очереди с коротким таймаутом видимости в 1 с List <QueueMessage> messages = new List <QueueMessage>(); Response <QueueMessage[]> received = await queue.ReceiveMessagesAsync(10, visibilityTimeout : TimeSpan.FromSeconds(1)); foreach (QueueMessage message in received.Value) { // Сообщаем сервису, что нам нужно немного больше времени на обработку сообщения, // указывая для него окно видимости в 5 с UpdateReceipt receipt = await queue.UpdateMessageAsync( message.MessageId, message.PopReceipt, message.MessageText, TimeSpan.FromSeconds(5)); // Keep track of the updated messages messages.Add(message.Update(receipt)); } // Ждем, пока исходное окно видимости в 1 с истечет и проверяем, // что сообщения еще не видимы //для этого повторно инициируем получение сообщений await Task.Delay(TimeSpan.FromSeconds(1.5)); Assert.AreEqual(0, (await queue.ReceiveMessagesAsync(10)).Value.Length); // Finish processing the messages foreach (QueueMessage message in messages) { // "Обрабатываем" сообщения Console.WriteLine($"Message: {message.MessageText}"); // Заканчиваем обработку сообщений, удаляя их и очереди await queue.DeleteMessageAsync(message.MessageId, message.PopReceipt); } }