Esempio n. 1
0
        /// <summary>
        /// Demostrate how to manually Create <see cref="ServiceBusProcessor"/>.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task ProcessAsync(CancellationToken cancellationToken)
        {
            // 1. named value of the connection
            var client = _connections.CreateClient(ServiceBusNames.QueuesOnly);

            var options = new ServiceBusProcessorOptions
            {
                AutoCompleteMessages = false,
                MaxConcurrentCalls   = 1
            };

            // 2. Topic or Queue Name
            var processor = client.CreateProcessor("sendgridwebhook_dev", options);

            processor.ProcessMessageAsync += MessageHandler;
            processor.ProcessErrorAsync   += ErrorHandler;

            async Task MessageHandler(ProcessMessageEventArgs args)
            {
                var body = args.Message.Body.ToString();

                _logger.LogInformation(body);

                // we can evaluate application logic and use that to determine how to settle the message.
                await args.CompleteMessageAsync(args.Message);
            }

            Task ErrorHandler(ProcessErrorEventArgs args)
            {
                // the error source tells me at what point in the processing an error occurred
                _logger.LogInformation(args.ErrorSource.ToString());
                // the fully qualified namespace is available
                _logger.LogInformation(args.FullyQualifiedNamespace);
                // as well as the entity path
                _logger.LogInformation(args.EntityPath);
                _logger.LogInformation(args.Exception.ToString());
                return(Task.CompletedTask);
            }

            // start processing
            await processor.StartProcessingAsync();
        }
        public async Task PublishAsync(
            string queueName,
            QueueEvent @event,
            CancellationToken cancellationToken = default)
        {
            var eventName   = @event.GetType().Name.Replace(_QUEUEEVENTSUFFIX, string.Empty);
            var jsonMessage = JsonConvert.SerializeObject(@event);
            var body        = Encoding.UTF8.GetBytes(jsonMessage);

            var message = new Message
            {
                MessageId = Guid.NewGuid().ToString(),
                Body      = body,
                Label     = eventName,
            };

            var client = _connection.CreateClient(queueName);

            cancellationToken.ThrowIfCancellationRequested();

            await client.SendAsync(message);
        }
Esempio n. 3
0
        public async Task SendMessagesAsync <T>(
            IList <T> messages,
            string subject = "",
            CancellationToken cancellationToken = default)
        {
            var messageTypes = messages.Select(m => m?.GetType()).Distinct();

            EnsureMessagesAreMapped(messageTypes);

            var queuedMessages = new Queue <ServiceBusMessage>();
            var producerInfo   = _mappings[Named].Find(x => x.MessageType == typeof(T));

            foreach (var message in messages)
            {
                var queuedMessage = new JsonSerializedMessage <T>(message);

                if (!string.IsNullOrEmpty(producerInfo?.Subscription))
                {
                    queuedMessage.Subject = producerInfo.Subscription;
                }

                if (!string.IsNullOrEmpty(subject))
                {
                    queuedMessage.Subject = subject;
                }

                queuedMessages.Enqueue(queuedMessage);
            }

            var client = _connection.CreateClient(Named);

            var sender = client.CreateSender(producerInfo.QueueOrTopicName);

            // create a message batch that we can send
            // total number of messages to be sent to the Service Bus queue
            var messageCount = messages.Count;

            // while all messages are not sent to the Service Bus queue
            while (queuedMessages.Count > 0)
            {
                // start a new batch
                using var messageBatch = await sender.CreateMessageBatchAsync(cancellationToken);

                // add the first message to the batch
                if (messageBatch.TryAddMessage(queuedMessages.Peek()))
                {
                    // dequeue the message from the .NET queue once the message is added to the batch
                    queuedMessages.Dequeue();
                }
                else
                {
                    // if the first message can't fit, then it is too large for the batch
                    throw new Exception($"Message {messageCount - messages.Count} is too large and cannot be sent.");
                }

                // add as many messages as possible to the current batch
                while (queuedMessages.Count > 0 && messageBatch.TryAddMessage(queuedMessages.Peek()))
                {
                    // dequeue the message from the .NET queue as it has been added to the batch
                    queuedMessages.Dequeue();
                }

                // now, send the batch
                await sender.SendMessagesAsync(messageBatch, cancellationToken);

                // if there are any remaining messages in the .NET queue, the while loop repeats
            }
        }