Exemplo n.º 1
0
        public void Consume()
        {
            var channel = _connection.CreateModel();

            channel.QueueDeclare(queue: EventBusConstant.BasketChekoutQueue, durable: false, exclusive: false, autoDelete: false, arguments: null);
            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += ReceivedEvent;
            channel.BasicConsume(queue: EventBusConstant.BasketChekoutQueue, autoAck: true, consumer: consumer,
                                 noLocal: false,
                                 exclusive: false, arguments: null);
        }
        public void Consume()
        {
            var channel = _connection.CreateModel();

            channel.QueueDeclare(EventBusConstans.BasketCheckoutQueue, false, false,
                                 false, null);

            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += RecievedEvent;

            channel.BasicConsume(EventBusConstans.BasketCheckoutQueue, true, consumer);
        }
        //public EventBusRabbitMQConsumer(IRabbitMQConnection connection, IMediator mediator, IMapper mapper)
        //{
        //    _connection = connection ?? throw new ArgumentNullException(nameof(connection));
        //    _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        //    _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        //}

        public void Consume()
        {
            var channel = _connection.CreateModel();

            channel.QueueDeclare(queue: EventBusConstants.UpdateIssueInSprintQueue, durable: false, exclusive: false, autoDelete: false, arguments: null);

            var consumer = new EventingBasicConsumer(channel);

            //Create event when something receive
            consumer.Received += ReceivedEvent;

            channel.BasicConsume(queue: EventBusConstants.UpdateIssueInSprintQueue, autoAck: true, consumer: consumer);
        }
Exemplo n.º 4
0
        public void Consume()
        {
            var channel = _connection.CreateModel();

            channel.QueueDeclare("test", false, false, false, null);
            var consumer = new EventingBasicConsumer(channel);

            channel.QueueDeclare(EventBusConsts.SendEmailQueque, false, false, false, null);
            channel.BasicConsume(queue: EventBusConsts.SendEmailQueque, autoAck: true, consumer: consumer);
            consumer.Received += ReceivedEvent;

            // channel.BasicConsume(EventBusConsts.SendEmailQueque, true, consumer);
        }
Exemplo n.º 5
0
        /// <summary/>
        public void Publish(RabbitMQEvent @event)
        {
            if (!CanConnect)
            {
                return;
            }

            OpenRabbitMQConnectionIfItIsNotOpened();

            var policy = Policy.Handle <BrokerUnreachableException>().Or <SocketException>()
                         .WaitAndRetry(_connection.RetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                _logger.LogWarning(ex, "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, $"{time.TotalSeconds:n1}", ex.Message);
            });

            var eventName = @event.GetType().Name;

            _logger.LogTrace("Creating RabbitMQ channel to publish event: {EventId} ({EventName})", @event.Id, eventName);

            using var channel = _connection.CreateModel();
            channel.ExchangeDeclare(exchange: SingeAplicationName, type: ExchangeType.Direct);

            var message     = JsonConvert.SerializeObject(@event);
            var messageBody = Encoding.UTF8.GetBytes(message);

            policy.Execute(() =>
            {
                var properties          = channel.CreateBasicProperties();
                properties.DeliveryMode = 2; // persistent

                channel.BasicPublish(
                    exchange: SingeAplicationName,
                    routingKey: eventName,
                    mandatory: true,
                    basicProperties: properties,
                    body: messageBody);
            });
        }
Exemplo n.º 6
0
        public void Publish(IEvent @event)
        {
            var eventName = @event.GetType().Name;

            _logger.LogInformation($"Executando { nameof(Publish) }({eventName})");

            if (_connection.Disconnected)
            {
                _connection.Connect();
            }

            var policy = Policy.Handle <BrokerUnreachableException>()
                         .Or <SocketException>()
                         .WaitAndRetry(3, attemp => TimeSpan.FromSeconds(Math.Pow(2, attemp)), (ex, time) =>
            {
                _logger.LogWarning("Não foi possível publicar a '{EventName}': ({ExceptionMessage})", eventName, ex.Message);
            });


            using (var channel = _connection.CreateModel())
            {
                DeclareExchange(channel);

                DeclareQueueAndBind(eventName, channel);

                policy.Execute(() =>
                {
                    _logger.LogInformation("Publicando '{EventName}': {Event}", eventName, @event.ToJson());

                    channel.BasicPublish(
                        exchange: EXCHANGE_NAME,
                        routingKey: eventName,
                        basicProperties: null,
                        body: @event.ToJson(IgnoredProperties).ToBytes()
                        );
                });
            }
        }
Exemplo n.º 7
0
        public void PublishBasketCheckout(string queueName, BasketCheckoutEvent publishModel)
        {
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
                var message = JsonConvert.SerializeObject(publishModel);
                var body    = Encoding.UTF8.GetBytes(message);

                IBasicProperties properties = channel.CreateBasicProperties();
                properties.Persistent   = true;
                properties.DeliveryMode = 2;

                channel.ConfirmSelect();
                channel.BasicPublish(exchange: "", routingKey: queueName, mandatory: true, basicProperties: properties, body: body);
                channel.WaitForConfirmsOrDie();

                channel.BasicAcks += (sender, args) =>
                {
                    Console.WriteLine("Sent RabbitMQ");
                };
                channel.ConfirmSelect();
            }
        }
        public void Consume()
        {
            // Open new channel
            var channel = _connection.CreateModel();

            // Read queue
            channel.QueueDeclare(queue: EventBusConstants.BasketCheckoutQueue, durable: false, exclusive: false, autoDelete: false, arguments: null);

            var consumer = new EventingBasicConsumer(channel);

            // Attach main event, get RabbitMQ message
            consumer.Received += ReceivedEvent;

            channel.BasicConsume(queue: EventBusConstants.BasketCheckoutQueue, autoAck: true, consumer: consumer);
        }
Exemplo n.º 9
0
        public void PublishBasketCheckout(string queueName, BasketCheckoutEvent checkoutEvent)
        {
            using IModel channel = connection.CreateModel();
            channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
            string message = JsonConvert.SerializeObject(checkoutEvent);

            byte[] body = Encoding.UTF8.GetBytes(message);

            IBasicProperties properties = channel.CreateBasicProperties();

            properties.Persistent   = true;
            properties.DeliveryMode = 2;

            channel.ConfirmSelect();
            channel.BasicPublish(exchange: "", routingKey: queueName, mandatory: true, basicProperties: properties, body: body);
            channel.WaitForConfirmsOrDie();

            channel.BasicAcks += (sender, ebentArgs) =>
            {
                Console.WriteLine("Sent RabitMQ");
                //implement acks handle
            };

            channel.ConfirmSelect();

            //using (IModel channel = connection.CreateModel())
            //{
            //    channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
            //    string message = JsonConvert.SerializeObject(checkoutEvent);
            //    byte[] body = Encoding.UTF8.GetBytes(message);

            //    IBasicProperties properties = channel.CreateBasicProperties();
            //    properties.Persistent = true;
            //    properties.DeliveryMode = 2;

            //    channel.ConfirmSelect();
            //    channel.BasicPublish(exchange: "", routingKey: queueName, mandatory: true, basicProperties: properties, body: body);
            //    channel.WaitForConfirmsOrDie();

            //    channel.BasicAcks += (sender, ebentArgs) =>
            //    {
            //        Console.WriteLine("Sent RabitMQ");
            //        //implement acks handle
            //    };

            //    channel.ConfirmSelect();
            //}
        }
Exemplo n.º 10
0
 public RpcClient(IRabbitMQConnection connection)
 {
     _connection        = connection;
     channel            = connection.CreateModel();
     replyQueueName     = channel.QueueDeclare().QueueName;
     consumer           = new EventingBasicConsumer(channel);
     consumer.Received += (model, ea) =>
     {
         if (!callbackMapper.TryRemove(ea.BasicProperties.CorrelationId, out TaskCompletionSource <string> tcs))
         {
             return;
         }
         var body     = ea.Body.ToArray();
         var response = Encoding.UTF8.GetString(body);
         tcs.TrySetResult(response);
     };
 }
        private IModel CreateConsumerChannel()
        {
            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }

            var channel = _connection.CreateModel();

            channel.QueueDeclare(
                queue: _queueName,
                durable: true,
                exclusive: false,
                autoDelete: false,
                arguments: null);

            return(channel);
        }
Exemplo n.º 12
0
        public void Consume()
        {
            var channel = _connection.CreateModel();

            channel.QueueDeclare(queue: EventBusConstants.BasketCheckoutQueue,
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            var consumer = new EventingBasicConsumer(channel);

            //Create Event when something received
            consumer.Received += Consumer_Received;

            channel.BasicConsume(queue: EventBusConstants.BasketCheckoutQueue,
                                 autoAck: true,
                                 consumer: consumer);
        }
Exemplo n.º 13
0
        public void Consume()
        {
            // _logger.LogCDCIError("test log");
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(queue: EventBusConstants.SmsQue, durable: true, exclusive: false, autoDelete: false, arguments: null);

                channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

                Console.WriteLine(" [*] Waiting for messages.");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += ReceivedEvent;
                channel.BasicConsume(queue: EventBusConstants.SmsQue, autoAck: false, consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
        }
        public void PublishPrepareReport(string queueName, PrepareReportEvent publishModel)
        {
            //create channel to perform the queue operations
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, null);
                var message = JsonConvert.SerializeObject(publishModel);
                var body    = Encoding.UTF8.GetBytes(message);

                IBasicProperties properties = channel.CreateBasicProperties();
                properties.Persistent   = true;
                properties.DeliveryMode = 2;

                channel.ConfirmSelect();
                channel.BasicPublish(exchange: "", routingKey: queueName, mandatory: true, basicProperties: properties, body: body);
                channel.WaitForConfirmsOrDie();
                channel.ConfirmSelect();
            }
        }
        public void PublishBasketCheckout(string queueName, BasketCheckoutEvent publishModel)
        {
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare
                (
                    queue: queueName,
                    durable: false,
                    exclusive: false,
                    autoDelete: false,
                    arguments: null
                );

                string serializedMessage = JsonConvert.SerializeObject(publishModel);

                Console.WriteLine("[EventBusRabbitMQProducer][PublishBasketCheckout] => (serializedMessage): ");
                Console.WriteLine(serializedMessage);
                Console.WriteLine("");

                byte[] messageByteArray = Encoding.UTF8.GetBytes(serializedMessage);

                IBasicProperties basicProps = channel.CreateBasicProperties();
                basicProps.Persistent   = true;
                basicProps.DeliveryMode = 2;

                channel.ConfirmSelect();
                channel.BasicPublish
                (
                    exchange: "",
                    routingKey: queueName,
                    mandatory: true,
                    basicProperties: basicProps,
                    body: messageByteArray
                );
                channel.WaitForConfirmsOrDie();

                channel.BasicAcks += (sender, eventArgs) =>
                {
                    Console.WriteLine("[EventBusRabbitMQProducer][PublishBasketCheckout] => (IN 'channel.BasicAcks')");
                };
                channel.ConfirmSelect();
            }
        }
        private IModel CreateChannel(Type @event)
        {
            Init(@event);
            _persistentConnection.TryConnect();

            var channel = _persistentConnection.CreateModel();

            channel.ExchangeDeclare(exchange: BROKER_NAME, type: ExchangeType.Direct);
            channel.QueueDeclare(_queueName, true, false, false, null);
            channel.QueueBind(_queueName, BROKER_NAME, _queueName, null);

            channel.CallbackException += (sender, ea) =>
            {
                _consumerChannel.Dispose();
                _consumerChannel = CreateChannel(@event);
            };

            return(channel);
        }
Exemplo n.º 17
0
 public void Publish <T>(T @event) where T : Event
 {
     try
     {
         if (!_persistentConnection.IsConnected)
         {
             _persistentConnection.TryConnect();
         }
         var policy = RetryPolicy.Handle <BrokerUnreachableException>()
                      .Or <SocketException>()
                      .WaitAndRetry(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
         {
             // _logger.LogWarning(ex, "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, $"{time.TotalSeconds:n1}", ex.Message);
         });
         //var factory = new ConnectionFactory() { HostName = "rabbitmqX", Port = 5672 };
         //factory.UserName = "******";
         //factory.Password = "******";
         //factory.AutomaticRecoveryEnabled = true;
         //factory.TopologyRecoveryEnabled = true;
         //factory.NetworkRecoveryInterval = TimeSpan.FromSeconds(5);
         //factory.UseBackgroundThreadsForIO = true;
         //factory.RequestedHeartbeat = 2;
         // using (var connection = factory.CreateConnection())
         using (var channel = _persistentConnection.CreateModel())
         {
             policy.Execute(() =>
             {
                 var eventName = @event.GetType().Name;
                 channel.QueueDeclare(eventName, false, false, false, null);
                 var message = JsonConvert.SerializeObject(@event);
                 byte[] body = Encoding.UTF8.GetBytes(message);
                 channel.BasicPublish("", eventName, null, body);
             }
                            );
         }
         Console.WriteLine("publish");
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error : " + ex.Message);
     }
 }
Exemplo n.º 18
0
        public void PublishBasketCheckout(string queueName, BasketCheckoutEvent publishModel)
        {
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(queueName, false, false, false, null);
                var message = JsonConvert.SerializeObject(publishModel);
                var body    = Encoding.UTF8.GetBytes(message);

                var properties = channel.CreateBasicProperties();
                properties.Persistent   = true;
                properties.DeliveryMode = 2;

                channel.ConfirmSelect();
                channel.BasicPublish("", queueName, true, properties, body);
                channel.WaitForConfirmsOrDie();

                channel.BasicAcks += (sender, args) => { Console.WriteLine("Sent RabbitMQ"); };
                channel.ConfirmSelect();
            }
        }
Exemplo n.º 19
0
        public void PublishBasketCheckout(string queueName, BasketCheckoutEvent model)
        {
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(queueName, false, false, false, null);

                var properties = channel.CreateBasicProperties();
                properties.Persistent   = true;
                properties.DeliveryMode = 2; // persistent

                var message = JsonConvert.SerializeObject(model);
                var body    = Encoding.UTF8.GetBytes(message);

                channel.ConfirmSelect();
                channel.BasicPublish("", queueName, true, properties, body);
                channel.WaitForConfirmsOrDie();
                channel.BasicAcks += Channel_BasicAcks;
                channel.ConfirmSelect();
            }
        }
Exemplo n.º 20
0
        public void Consume()
        {
            var channel = _connection.CreateModel();

            channel.QueueDeclare(queue: "rpc_queue", durable: false, exclusive: false, autoDelete: false, arguments: null);
            channel.BasicQos(0, 1, false);
            var consumer = new EventingBasicConsumer(channel);

            channel.BasicConsume(queue: "rpc_queue", autoAck: false, consumer: consumer);

            consumer.Received += (model, ea) =>
            {
                string response = null;

                var body       = ea.Body.ToArray();
                var props      = ea.BasicProperties;
                var replyProps = channel.CreateBasicProperties();
                replyProps.CorrelationId = props.CorrelationId;

                try
                {
                    var message = Encoding.UTF8.GetString(body);
                    int id      = int.Parse(message);

                    ServiceResponse <Enums.UserType> res = _accountService.GetUserType(id);
                    response = JsonSerializer.Serialize(res);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error at RPC Server: " + e.Message);
                    response = "";
                }
                finally
                {
                    var responseBytes = Encoding.UTF8.GetBytes(response);
                    channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, basicProperties: replyProps, body: responseBytes);
                    channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                }
            };
        }
Exemplo n.º 21
0
        public RabbitMQEventPublisher(
            IRabbitMQConnection connection,
            ILogger <RabbitMQEventPublisher> logger,
            string exchangeName,
            string queueName = null)
        {
            _connection   = connection ?? throw new ArgumentNullException(nameof(connection));
            _logger       = logger ?? throw new ArgumentNullException(nameof(logger));
            _exchangeName = exchangeName;

            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }
            using var channel = _connection.CreateModel();

            // create exchange
            channel.ExchangeDeclare(
                exchange: _exchangeName,
                type: "topic");

            // create queue and bind to exchange if necessary
            if (!string.IsNullOrWhiteSpace(queueName))
            {
                channel.QueueDeclare(
                    queue: queueName,
                    durable: true,
                    exclusive: false,
                    autoDelete: false,
                    arguments: null);

                channel.QueueBind(
                    queue: queueName,
                    exchange: exchangeName,
                    routingKey: "#",
                    arguments: null
                    );
            }
        }
        public void PublishBasketCheckout(string queueName, BasketCheckoutEvent publishModel)
        {
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(
                    queue: queueName,
                    durable: false,
                    exclusive: false,
                    autoDelete: false,
                    arguments: null
                    );
                var message = JsonConvert.SerializeObject(publishModel);
                var body    = Encoding.UTF8.GetBytes(message);

                IBasicProperties properties = channel.CreateBasicProperties();
                properties.Persistent   = true;
                properties.DeliveryMode = 2;

                // https://rabbitmq.com/tutorials/amqp-concepts.html
                channel.ConfirmSelect();
                channel.BasicPublish(
                    exchange: "",                     // Direct exchg (empty str == amq.direct)
                    routingKey: queueName,
                    mandatory: true,
                    basicProperties: properties,
                    body: body
                    );
                channel.WaitForConfirmsOrDie();

                channel.BasicAcks += (sender, EventArgs) =>
                {
                    Console.WriteLine("Sent msg acknowledge to RabbitMQ");
                    //implement ack handle
                };
                channel.ConfirmSelect();
            }
        }
Exemplo n.º 23
0
        public void PublishBasketCheckout(string queueName, BasketCheckoutEvent checkoutEvent)
        {
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(queueName, false, false, false, null);


                channel.ConfirmSelect();

                var props = channel.CreateBasicProperties();
                props.Persistent   = true;
                props.DeliveryMode = 2;

                channel.BasicAcks += (sender, eventArgs) =>
                {
                    Console.WriteLine("Basket Checkout Event has been Published Successfully !");
                };

                channel.BasicPublish("", queueName, true, props, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(checkoutEvent)));
                channel.WaitForConfirmsOrDie();

                channel.ConfirmSelect();
            }
        }
Exemplo n.º 24
0
 public void Publish <T>(string queueName, T publishModel) where T : class
 {
     using (var channel = _connection.CreateModel())
     {
         channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: default);