public Task <bool> ReceiveMessageAsync()
        {
            try
            {
                _logger.LogInformation($"Begin to receive the message queue of Rabbit MQ: {_connectString}");
                var factory = new ConnectionFactory()
                {
                    HostName = _connectString, DispatchConsumersAsync = true
                };
                using var connection = factory.CreateConnection();
                using var channel    = connection.CreateModel();
                Console.WriteLine("======================================================");
                Console.WriteLine("Press ENTER key to exit after receiving all the messages of RabbitMQ.");
                Console.WriteLine("======================================================");
                _logger.LogInformation($"Declare a new chanel with queue name {_queueName}");
                channel.QueueDeclare(queue: _queueName,
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                var consumer = new AsyncEventingBasicConsumer(channel);
                consumer.Received += async(model, ea) =>
                {
                    var body = ea.Body;//Maybe fix "Convert ReadOnlyMemory<byte> to byte[]": .ToArray()

                    var messageBody = Encoding.UTF8.GetString(body.Span);

                    //    await SaveData.Execute(messageBody, _bookService);
                    _logger.LogInformation($"Start to process the message body: {messageBody}");
                    await _saveData.ExecuteQuery(messageBody);
                };
                channel.BasicConsume(queue: _queueName,
                                     autoAck: true,
                                     consumer: consumer);
                _logger.LogInformation($"End Rabbit MQ");
                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                _logger.LogError($"An error occurred {ex.Message}");
                throw ex;
            }

            return(Task.FromResult(true));
        }
        async System.Threading.Tasks.Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            string messageBody = Encoding.UTF8.GetString(message.Body);
            // Console.WriteLine(messageInfo.actionType.ToUpper() + " successful." + Environment.NewLine);
            // Complete the message so that it is not received again.
            // This can be done only if the queue Client is created in ReceiveMode.PeekLock mode (which is the default).
            await queueClient.CompleteAsync(message.SystemProperties.LockToken);

            //  _logger.LogInformation($"Saved message Number: {message.SystemProperties.SequenceNumber}");
            //Console.WriteLine($"Saved message Number: {message.SystemProperties.SequenceNumber}"+ Environment.NewLine);
            // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
            // If queueClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
            // Process the message.
            _logger.LogInformation($"Start to process the message body: {messageBody}");
            await _saveData.ExecuteQuery(messageBody);
        }
Exemplo n.º 3
0
        public Task <bool> ReceiveMessageAsync()
        {
            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages of NATS.");
            Console.WriteLine("======================================================");
            // Create a new connection factory to create
            // a connection.
            ConnectionFactory cf = new ConnectionFactory();

            // Creates a live connection to the default
            // NATS Server running locally
            _client = cf.CreateConnection(_connectionString);
            // Setup an event handler to process incoming messages.
            // An anonymous delegate function is used for brevity.
            EventHandler <MsgHandlerEventArgs> h = (sender, args) =>
            {
                // print the message
                //Console.WriteLine(args.Message);
                var messageBody = Encoding.UTF8.GetString(args.Message.Data);
                _saveData.ExecuteQuery(messageBody);
                // Here are some of the accessible properties from
                // the message:
                // args.Message.Data;
                // args.Message.Reply;
                // args.Message.Subject;
                // args.Message.ArrivalSubcription.Subject;
                // args.Message.ArrivalSubcription.QueuedMessageCount;
                // args.Message.ArrivalSubcription.Queue;

                // Unsubscribing from within the delegate function is supported.
                // args.Message.ArrivalSubcription.Unsubscribe();
            };
            // The simple way to create an asynchronous subscriber
            // is to simply pass the event in.  Messages will start
            // arriving immediately.
            IAsyncSubscription s = _client.SubscribeAsync(_queueName, h);

            Console.ReadLine();
            s.Unsubscribe();
            return(Task.FromResult(true));
        }