Esempio n. 1
0
        //private void Close()
        //{
        //    _chanel.Close();
        //    _connection.Close();
        //}

        public void SendMessage(string queueName, string message)
        {
            Open();
            //todo 发送消息
            _chanel.QueueDeclare(queueName, false, false, true, null);
            var bytes = Encoding.UTF8.GetBytes(message);

            _chanel.BasicPublish("", queueName, null, bytes);
            //Console.WriteLine("发送消息");
            //Close();
        }
Esempio n. 2
0
        private static void PullMQ()
        {
            Console.WriteLine("Begin pull all msg...");

            var MQQueueName = ConfigurationManager.AppSettings["MQQueueName"];
            var factory     = MQUtils.MQFactory;

            using (var conn = factory.CreateConnection())
            {
                using (RabbitMQ.Client.IModel channel = conn.CreateModel())
                {
                    IDictionary <string, object> queueArgs = new Dictionary <string, object>
                    {
                        { "x-ha-policy", "all" }
                    };
                    channel.QueueDeclare(queue: MQQueueName,
                                         durable: true,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: queueArgs);
                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
                    while (!MQUtils.QueueEmpty())
                    {
                        if (!MQUtils.Pull(channel, ExcuteMessage))
                        {
                            Console.WriteLine("{0} - Queue is empty!", Thread.CurrentThread.ManagedThreadId);
                            Thread.Sleep(1000);
                        }
                    }
                    Console.WriteLine("pull all msg done!");
                }
            }
        }
 public void PublishEvent <T>(T @event) where T : IEvent
 {
     using (IConnection conn = connectionFactory.CreateConnection())
     {
         using (RabbitMQ.Client.IModel channel = conn.CreateModel())
         {
             var queue = @event is CustomerCreatedEvent ?
                         Constants.QUEUE_CUSTOMER_CREATED : @event is CustomerUpdatedEvent ?
                         Constants.QUEUE_CUSTOMER_UPDATED : Constants.QUEUE_CUSTOMER_DELETED;
             channel.QueueDeclare(
                 queue: queue,
                 durable: false,
                 exclusive: false,
                 autoDelete: false,
                 arguments: null
                 );
             var body = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(@event));
             channel.BasicPublish(
                 exchange: "",
                 routingKey: queue,
                 basicProperties: null,
                 body: body
                 );
         }
     }
 }
Esempio n. 4
0
        } // AmqpClient

        #region ConnectionHandlerProgram

        private Exception MakeNewConnection(ref RmqCl.IConnection connection, ref RmqCl.IModel channel, bool reconnecting)
        {
            // This method attempts to make a new connection. Returns true if success, otherwise false.

            var connRequest = ConnectionRequestObj;

            var factory = new RmqCl.ConnectionFactory()
            {
                HostName = connRequest.Host,
                UserName = connRequest.Username,
                Password = connRequest.Password
            };

            // Secure connection?
            if (connRequest.Secure)
            {
                factory.Ssl.Enabled    = true;
                factory.Ssl.ServerName = connRequest.Host;
                factory.Ssl.Version    = System.Security.Authentication.SslProtocols.Tls12;
            }

            try
            {
                // Create connection and channel
                connection = factory.CreateConnection();
                channel    = connection.CreateModel();

                // Declare the exchange
                channel.ExchangeDeclare(exchange: connRequest.Exchange, type: "topic", autoDelete: false, durable: true, arguments: null);

                // Create a queue to receive messages
                var queueName = channel.QueueDeclare(queue: "",        // Use a generated queue name
                                                     durable: false,   // The queue does not survive a broker restart
                                                     exclusive: true,  // The queue is only for this application, and it will be deleted on app exit
                                                     autoDelete: true, // The queue is deleted when no one is bound to it
                                                     arguments: null
                                                     ).QueueName;

                // Bind the queue to the topic pattern
                channel.QueueBind(queue: queueName, exchange: connRequest.Exchange, routingKey: connRequest.TopicPattern, arguments: null);

                // Set up a consumer for messages
                m_messageConsumer           = new RmqCl.Events.EventingBasicConsumer(channel);
                m_messageConsumer.Received += MessageReceived;
                channel.BasicConsume(queue: queueName, noAck: true, consumerTag: "", noLocal: false, exclusive: false, arguments: new Dictionary <string, object> {
                }, consumer: m_messageConsumer);

                // Sign up for the shutdown event
                channel.ModelShutdown += ModelShutdown; // This event will fire if the connection is lost

                return(null);
            }
            catch (Exception e)
            {
                // Clean the connection
                DestroyConnection(ref connection, ref channel);

                return(e);
            }
        } // MakeNewConnection
        private void InitializeWorkerQueue(IModel channel)
        {
            var mainQueueArgs = new Dictionary <string, object> {
                { "x-dead-letter-exchange", $"{_serviceName}.Dlx.E.Fanout.{Env}" }
            };

            channel.QueueDeclare(
                queue: $"{_serviceName}.Queue.{Env}",
                durable: true,
                exclusive: false,
                autoDelete: false,
                arguments: mainQueueArgs);
        }
Esempio n. 6
0
        private List <RC.QueueDeclareOk> DeclareQueues(RC.IModel channel, params IQueue[] queues)
        {
            var declareOks = new List <RC.QueueDeclareOk>(queues.Length);

            for (var i = 0; i < queues.Length; i++)
            {
                var queue = queues[i];
                if (!queue.QueueName.StartsWith("amq."))
                {
                    _logger?.LogDebug("Declaring Queue '{queueName}'", queue.QueueName);

                    if (queue.QueueName.Length > 255)
                    {
                        throw new ArgumentException("Queue names limited to < 255 characters");
                    }

                    try
                    {
                        try
                        {
                            var declareOk = channel.QueueDeclare(queue.QueueName, queue.IsDurable, queue.IsExclusive, queue.IsAutoDelete, queue.Arguments);
                            if (!string.IsNullOrEmpty(declareOk.QueueName))
                            {
                                queue.ActualName = declareOk.QueueName;
                            }

                            declareOks.Add(declareOk);
                        }
                        catch (ArgumentException)
                        {
                            CloseChannelAfterIllegalArg(channel, queue);
                            throw;
                        }
                    }
                    catch (Exception e)
                    {
                        LogOrRethrowDeclarationException(queue, "queue", e);
                    }
                }
                else
                {
                    _logger?.LogDebug("Queue with name: {queueName} that starts with 'amq.' cannot be declared.", queue.QueueName);
                }
            }

            return(declareOks);
        }
        private void InitializeDeadLetterQueue(IModel channel)
        {
            var dlqQueueArgs = new Dictionary <string, object> {
                { "x-dead-letter-exchange", $"{_serviceName}.Input.E.Direct.{Env}" },
                { "x-message-ttl", (int)TimeSpan.FromMinutes(1).TotalMilliseconds }
            };

            channel.QueueDeclare(
                queue: $"{_serviceName}.Dlq.Queue.{Env}",
                durable: true,
                exclusive: false,
                autoDelete: false,
                arguments: dlqQueueArgs);

            channel.QueueBind(queue: $"{_serviceName}.Dlq.Queue.{Env}",
                              exchange: $"{_serviceName}.Dlx.E.Fanout.{Env}",
                              routingKey: "");
        }