Main entry point to the RabbitMQ .NET AMQP client API. Constructs IConnection instances.

A simple example of connecting to a broker:

ConnectionFactory factory = new ConnectionFactory(); // // The next six lines are optional: factory.UserName = ConnectionFactory.DefaultUser; factory.Password = ConnectionFactory.DefaultPass; factory.VirtualHost = ConnectionFactory.DefaultVHost; factory.HostName = hostName; factory.Port = AmqpTcpEndpoint.UseDefaultPort; // IConnection conn = factory.CreateConnection(); // IModel ch = conn.CreateModel(); // // ... use ch's IModel methods ... // ch.Close(Constants.ReplySuccess, "Closing the channel"); conn.Close(Constants.ReplySuccess, "Closing the connection");

The same example, written more compactly with AMQP URIs:

ConnectionFactory factory = new ConnectionFactory(); factory.Uri = "amqp://localhost"; IConnection conn = factory.CreateConnection(); ...

Please see also the API overview and tutorial in the User Guide.

Note that the Uri property takes a string representation of an AMQP URI. Omitted URI parts will take default values. The host part of the URI cannot be omitted and URIs of the form "amqp://foo/" (note the trailling slash) also represent the default virtual host. The latter issue means that virtual hosts with an empty name are not addressable.

Esempio n. 1
1
 public Telegraph()
 {
     var connectionFactory = new ConnectionFactory { HostName = "localhost", VirtualHost = "test" };
     _connection = connectionFactory.CreateConnection();
     _channel = _connection.CreateModel();
     _consumer = new QueueingBasicConsumer(_channel);
 }
Esempio n. 2
1
        public void Disconnect()
        {
            if (_model != null)
            {
                lock (_model)
                {
                    _model.Close(200, "Goodbye");
                    _model.Dispose();
                }
                _model = null;
            }

            if (_connection != null)
            {
                lock (_connection)
                {
                    _connection.Close();
                    _connection.Dispose();
                }
                _connection = null;
            }

            if (_connectionFactory != null)
            {
                lock (_connectionFactory)
                {
                    _connectionFactory = null;
                }
            }
        }
        static void Main(string[] args)
        {
            var connectionfactory = new RabbitMQ.Client.ConnectionFactory()
            {
                Password = Password, UserName = UserName, HostName = HostName
            };
            var connection = connectionfactory.CreateConnection();
            var model      = connection.CreateModel();

            model.QueueDeclare("Module1.Sample3", true, false, false, null);
            Console.WriteLine("Queue Created");

            model.ExchangeDeclare("MyExchange", ExchangeType.Topic);
            Console.WriteLine("Exchange Created");

            model.QueueBind("Module1.Sample3", "MyExchange", "cars");
            Console.WriteLine("Exchange and Queue bound");

            //prop
            var properties = model.CreateBasicProperties();

#pragma warning disable CS0618 // Type or member is obsolete
            properties.SetPersistent(false);
#pragma warning restore CS0618 // Type or member is obsolete

            //serialize
            byte[] messageBuffer = Encoding.Default.GetBytes("this is my message");

            //send message
            model.BasicPublish(Exchange, QueueName, properties, messageBuffer);

            Console.WriteLine("Message Sent");
            Console.ReadLine();
        }
 /// <summary>
 /// Initialises a new instance of the <see cref="ConnectionFactory"/> class.
 /// </summary>
 public ConnectionFactory()
 {
     this.connectionFactory = new RabbitMQ.Client.ConnectionFactory
     {
         Uri = ConfigurationManager.AppSettings["CLOUDAMQP_URL"]
     };
 }
Esempio n. 5
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
Esempio n. 6
0
        public static void Receive2()
        {
            var factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    var queueDeclare = channel.QueueDeclare("task_queue", true, false, false, null);

                    //用于平衡调度,指定在接收端为处理完成之前不分配其他消息给该接收端
                    //如果不设置,假如有100条待处理记录,有两个接收端处理,无论两个接收端处理速度快慢,都同等分配50条
                    //如果设置该平衡调度,处理速度快的客户端会多分配
                    channel.BasicQos(0, 1, false);

                    var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received {0}", message);
                        channel.BasicAck(ea.DeliveryTag, false);

                        var i = Convert.ToInt32(message.Substring(message.Length - 1, 1));
                        System.Threading.Thread.Sleep((i % 2 == 1 ? 5 : 1) * 1000);
                    };
                    channel.BasicConsume(queue: queueDeclare.QueueName, noAck: false, consumer: consumer);
                    Console.WriteLine("consumer启动成功,Press [enter] to exit.");
                    Console.ReadLine(); //注意不要跳出,或者会释放资源,无法自动同步
                }
            }
        }
Esempio n. 7
0
        public void QueueMessage(string queueName, object messageContent)
        {
            //TODO: Hostname no config
            ConnectionFactory factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost", UserName = "******", Password = "******"
            };

            using (IConnection connection = factory.CreateConnection())
            {
                using (IModel modelChannel = connection.CreateModel())
                {
                    modelChannel.QueueBind(queue: queueName, exchange: "amq.direct", routingKey: queueName);

                    byte[] messageBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageContent));

                    IBasicProperties basicProp = modelChannel.CreateBasicProperties();
                    basicProp.ContentType  = "application/json";
                    basicProp.DeliveryMode = 2;

                    modelChannel.BasicPublish(exchange: "",
                                              routingKey: queueName,
                                              basicProperties: basicProp,
                                              body: messageBytes
                                              );
                }
            }
        }
Esempio n. 8
0
        private static void Setup()
        {
            string UserName = "******";
            string Password = "******";
            string HostName = "localhost";

            //Main entry point to the RabbitMQ .NET AMQP client
            var connectionFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                UserName = UserName,
                Password = Password,
                HostName = HostName
                           //Port = 6000
            };

            var connection = connectionFactory.CreateConnection();
            var model      = connection.CreateModel();

            Console.WriteLine("Creating Exchange");

            // Create Exchange
            model.ExchangeDeclare("Tom", ExchangeType.Direct);
            model.QueueDeclare("Jen", true, false, false, null);
            Console.WriteLine("Creating Queue");
            model.QueueBind("demoqueue", "demoExchange", "directexchange_key");
            Console.WriteLine("Creating Binding");
        }
Esempio n. 9
0
        private static void SendMessage()
        {
            string UserName = "******";
            string Password = "******";
            string HostName = "localhost";

            //Main entry point to the RabbitMQ .NET AMQP client
            var connectionFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                UserName = UserName,
                Password = Password,
                HostName = HostName
                           //Port = 6000
            };

            var connection = connectionFactory.CreateConnection();
            var model      = connection.CreateModel();
            var properties = model.CreateBasicProperties();

            properties.Persistent = false;
            byte[] messagebuffer = Encoding.Default.GetBytes("Direct Message" + DateTime.Now);

            model.BasicPublish("demoExchange", "directexchange_key", properties, messagebuffer);
            Console.WriteLine("Message Sent");

            var message = model.BasicGet("demoqueue", true);

            Console.WriteLine("message: " + Encoding.Default.GetString(message.Body));
        }
Esempio n. 10
0
        public static void Send2()
        {
            var factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //druable参数,用于持久化,如果为true,重启后,数据还在
                    //如果修改:如果为false重启服务可修改,如果true,需要进入到控制台,删除该列队
                    //注意:即便是设置为持久化,也有失去数据的可能,在接收到数据,写入磁盘之前,也有可能出现中断的情况
                    var queueDeclare = channel.QueueDeclare("task_queue", true, false, false, null);
                    var properties   = channel.CreateBasicProperties();
                    properties.Persistent = true; //配合QueueDeclare的druable参数使用,指定消息是否是持久化,如果为false,消息也不会被持久化

                    for (var i = 0; i < 10; i++)
                    {
                        var body = Encoding.UTF8.GetBytes("Messsage" + i);

                        channel.BasicPublish(exchange: "",
                                             routingKey: "task_queue",
                                             basicProperties: properties,
                                             body: body);
                        Console.WriteLine(" [x] Sent {0}", "Messsage" + i);
                    }
                }
            }

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
Esempio n. 11
0
        private void SetupRabbitMq()
        {
            var connectionFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                Password = Passowrd,
                UserName = UserName,
                HostName = HostName
            };

            if (!string.IsNullOrEmpty(VirtualHost))
            {
                connectionFactory.VirtualHost = VirtualHost;
            }

            if (port > 0)
            {
                connectionFactory.Port = port;
            }

            var connection = connectionFactory.CreateConnection();

            model = connection.CreateModel();

            //model.QueueDeclare(queueName, true, false, false, null);

            //model.ExchangeDeclare(exchangeName, ExchangeType.Topic);


            //model.QueueBind(queueName, exchangeName, "TestKey");
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory();
            factory.Protocol = Protocols.AMQP_0_9;
            factory.HostName = "localhost";
            factory.Port = AmqpTcpEndpoint.UseDefaultPort;

            using (var con = factory.CreateConnection())
            {
                using (var channel = con.CreateModel())
                {
                    SimpleRpcClient client = new SimpleRpcClient(channel, "test");

                    Console.WriteLine("Connected to the queue.  Type in a product name to submit an order or type 'q' + <ENTER> to quit...");
                    string productName = Console.ReadLine();
                    while (productName != "q")
                    {
                        byte[] body = ASCIIEncoding.ASCII.GetBytes(productName);
                        Console.WriteLine("Submitting order for product '{0}'...", productName);
                        var responseBody = client.Call(body);
                        string response = ASCIIEncoding.ASCII.GetString(responseBody);
                        Console.WriteLine("Response recieved.  Order ID: {0}", response);

                        productName = Console.ReadLine();
                    }

                }
            }
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            var factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "workqueue", durable: true, exclusive: false, autoDelete: false, arguments: null);
                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = true;

                    for (int i = 0; i < 1000; i++)
                    {
                        var message = "Message " + i.ToString();
                        var body    = System.Text.Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: "", routingKey: "workqueue", basicProperties: properties, body: body);
                    }

                    Console.WriteLine("All Messages Were Sent!");
                }
            }
            Console.ReadLine();
        }
Esempio n. 14
0
        static void SimpleSendMessage()
        {
            const string HostName     = "localhost";
            const string UserName     = "******";
            const string Password     = "******";
            const string QueueName    = "Module1.Sample3";
            const string ExchangeName = "";

            var connectionfactory = new RabbitMQ.Client.ConnectionFactory()
            {
                Password = Password,
                UserName = UserName,
                HostName = HostName
            };

            var connection = connectionfactory.CreateConnection();
            var model      = connection.CreateModel();

            Shared.Program.ConfigureQueues(model);
            var properties = model.CreateBasicProperties();

            properties.SetPersistent(true);

            // Serialize
            byte[] messageBuffer = Encoding.Default.GetBytes("This is my persistent message");
            // Send message
            model.BasicPublish(ExchangeName, QueueName, properties, messageBuffer);
            Console.WriteLine("Message sent...");
        }
Esempio n. 15
0
 static MessageManager()
 {
     connectionFactory = new ConnectionFactory()
     {
         HostName = Config.MATCHING_QUEUE_ADDRESS
     };
 }
Esempio n. 16
0
        public ConnectionFactory(
            string hostName    = "localhost",
            string password    = "******",
            int port           = 5672,
            string userName    = "******",
            string virtualHost = "/"
            )
        {
            var factory = new RabbitMQ.Client.ConnectionFactory
            {
                HostName    = hostName,
                Port        = port,
                VirtualHost = virtualHost,
                UserName    = userName,
                Password    = password
            };

            Connection = factory.CreateConnection();


            AppDomain.CurrentDomain.ProcessExit += (sender, args) => Dispose();
            Console.CancelKeyPress += (sender, args) =>
            {
                Dispose();
                args.Cancel = true;
            };
        }
Esempio n. 17
0
        public static void Run()
        {
            string UserName = "******";
            string Password = "******";
            string HostName = "localhost";

            var connectionFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                UserName = UserName,
                Password = Password,
                HostName = HostName
            };
            var connection = connectionFactory.CreateConnection();
            var model      = connection.CreateModel();
            //model.ExchangeDeclare("demoExchange", ExchangeType.Direct);

            //model.QueueDeclare("demoqueue", true, false, false, null);
            //Console.WriteLine("Creating Queue");

            //model.QueueBind("demoqueue", "demoExchange", "directexchange_key");
            //Console.WriteLine("Creating Binding");

            var properties = model.CreateBasicProperties();

            properties.Persistent = false;
            var messageBuffer = Encoding.Default.GetBytes("Direct Message");

            model.BasicPublish("demoExchange", "directexchange_key", properties, messageBuffer);
            Console.WriteLine("Message Sent");

            Console.ReadLine();
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            var factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //Exchange Deklare Edilir. Fanout tipinde bir exchange duzenlendi.
                    channel.ExchangeDeclare(exchange: "newsfanout", type: "fanout");
                    //Kuyruk Deklare edilir
                    channel.QueueDeclare(queue: "newsfanout_bbc", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    channel.QueueDeclare(queue: "newsfanout_newyorktimes", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    //ve Exchange ile İlişkilendirilir.
                    channel.QueueBind(queue: "newsfanout_bbc", exchange: "newsfanout", routingKey: "");
                    channel.QueueBind(queue: "newsfanout_newyorktimes", exchange: "newsfanout", routingKey: "");

                    for (int i = 0; i < 100; i++)
                    {
                        var message = "News " + i.ToString();
                        var body    = System.Text.Encoding.UTF8.GetBytes(message);
                        //Routing key burada onemsizlesiyor. Exchange dagitim işini devraldıgı için artık onun sorumlulugunda.
                        channel.BasicPublish(exchange: "newsfanout", routingKey: "", basicProperties: null, body: body);
                    }

                    Console.WriteLine("All Messages Were Sent!");
                    Console.ReadLine();
                }
            }
        }
Esempio n. 19
0
        public IConnection GetConnection(string productId)
        {
            if (!rabittmqConn.ContainsKey(productId))
            {
                if (!_settings.Products.ContainsKey(productId))
                {
                    throw new Exception(productId + " product setting not found");
                }
                var hKey = _settings.Products[productId].Host;
                if (!_settings.Hosts.ContainsKey(hKey))
                {
                    throw new Exception(hKey + " host setting not found");
                }
                var option  = _settings.Hosts[hKey];
                var factory = new RabbitMQ.Client.ConnectionFactory();
                factory.HostName                 = option.Address;
                factory.UserName                 = option.UserName;
                factory.Password                 = option.UserPassword;
                factory.VirtualHost              = option.VHost;
                factory.RequestedHeartbeat       = (ushort)option.Heartbeat;
                factory.AutomaticRecoveryEnabled = option.AutoRecovery;

                rabittmqConn[productId] = factory.CreateConnection();
            }


            return(rabittmqConn[productId]);
        }
Esempio n. 20
0
        public void ReceiveDataFromQueue()
        {
            string message = "";

            byte[] body        = null;
            var    connFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var conn = connFactory.CreateConnection())
                using (var channel = conn.CreateModel())
                {
                    channel.QueueDeclare("TestQue", false, false, false, null);
                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (ch, ea) =>
                    {
                        body = ea.Body;
                        // ... process the message

                        message = System.Text.Encoding.UTF8.GetString(body);
                        Console.WriteLine(message);
                        //channel.BasicAck(ea.DeliveryTag, false);
                    };
                    String consumerTag = channel.BasicConsume("TestQue", true, consumer);
                    Console.WriteLine("er r einsenheimmm");
                }
        }
Esempio n. 21
0
        public IConnection GetConnection(string productId)
        {
            if (this.disposedValue)
            {
                throw new ObjectDisposedException(nameof(CacheManager));
            }

            //if (!_cacheConn.ContainsKey(productId))
            //{
            //    if (!_settings.Products.ContainsKey(productId))
            //    {
            //        throw new Exception(productId + " product setting not found");
            //    }
            //    var hKey = _settings.Products[productId].Host;
            //    if (!_settings.Hosts.ContainsKey(hKey))
            //    {
            //        throw new Exception(hKey + " host setting not found");
            //    }
            //    _cacheConn[productId] = new CacheItem();
            //}
            var hKey    = _settings.Products[productId].Host;
            var option  = _settings.Hosts[hKey];
            var factory = new RabbitMQ.Client.ConnectionFactory();

            factory.HostName                 = option.Address;
            factory.UserName                 = option.UserName;
            factory.Password                 = option.UserPassword;
            factory.VirtualHost              = option.VHost;
            factory.RequestedHeartbeat       = (ushort)option.Heartbeat;
            factory.AutomaticRecoveryEnabled = option.AutoRecovery;
            //factory.ClientProperties["customerName"] = "aaaaaaa";
            return(factory.CreateConnection());
        }
Esempio n. 22
0
        public bool SendMessage(string message)
        {
            bool temp        = false;
            var  connFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var conn = connFactory.CreateConnection())
                using (var channel = conn.CreateModel())
                {
                    string name = "TestQue";
                    channel.QueueDeclare(name, false, false, false, null);
                    string messageToQueue = "First test message to queue";

                    byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(messageToQueue);
                    channel.BasicPublish("", name, null, byteMessage);
                    IBasicProperties props = channel.CreateBasicProperties();
                    props.ContentType  = "text/plain";
                    props.DeliveryMode = 2;
                    props.Expiration   = "36000000";
                    //channel.BasicPublish(name, "TestExchange", true, null, byteMessage);
                    temp = true;
                }
            return(temp);
        }
        public void Should_be_able_to_republish_message()
        {
            var serializer = new JsonSerializer();
            var error = serializer.BytesToMessage<Error>(Encoding.UTF8.GetBytes(errorMessage));

            var connectionFactory = new ConnectionFactory
            {
                HostName = "localhost",
                UserName = "******",
                Password = "******"
            };

            using (var connection = connectionFactory.CreateConnection())
            using (var model = connection.CreateModel())
            {
                try
                {
                    model.ExchangeDeclarePassive(error.Exchange);

                    var properties = model.CreateBasicProperties();
                    error.BasicProperties.CopyTo(properties);

                    var body = Encoding.UTF8.GetBytes(error.Message);

                    model.BasicPublish(error.Exchange, error.RoutingKey, properties, body);
                }
                catch (OperationInterruptedException)
                {
                    Console.WriteLine("The exchange, '{0}', described in the error message does not exist on '{1}', '{2}'",
                        error.Exchange, connectionFactory.HostName, connectionFactory.VirtualHost);
                }
            }
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            var connectionFactory = new ConnectionFactory();
            IConnection connection = connectionFactory.CreateConnection();
            IModel channel = connection.CreateModel();

            channel.ExchangeDeclare("topic-exchange-example", ExchangeType.Topic, false, true, null);
            channel.QueueDeclare("log", false, false, true, null);
            channel.QueueBind("log", "topic-exchange-example", "*.Personal.*");

            var consumer = new QueueingBasicConsumer(channel);
            channel.BasicConsume("log", true, consumer);

            Console.WriteLine("I am the Personal Consumer");

            while (true)
            {
                try
                {
                    var eventArgs = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    string message = Encoding.UTF8.GetString(eventArgs.Body);
                    Console.WriteLine(string.Format("{0} - {1}", eventArgs.RoutingKey, message));
                }
                catch (EndOfStreamException)
                {
                    // The consumer was cancelled, the model closed, or the connection went away.
                    break;
                }
            }

            channel.Close();
            connection.Close();
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            var factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //Exchange Deklare Edilir. Direct tipinde bir exchange duzenlendi.
                    channel.ExchangeDeclare(exchange: "newsdirect", type: "direct");
                    //Kuyruk Deklare edilir
                    channel.QueueDeclare(queue: "newsdirect_bbc", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    channel.QueueDeclare(queue: "newsdirect_nyt", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    //ve Exchange ile İlişkilendirilir.
                    channel.QueueBind(queue: "newsdirect_bbc", exchange: "newsdirect", routingKey: "bbc");
                    channel.QueueBind(queue: "newsdirect_nyt", exchange: "newsdirect", routingKey: "nyt");

                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, msg) =>
                    {
                        var message = System.Text.Encoding.UTF8.GetString(msg.Body);
                        Console.WriteLine(message);
                    };
                    channel.BasicConsume(queue: "newsdirect_bbc", autoAck: true, consumer: consumer);
                    Console.ReadLine();
                }
            }
        }
Esempio n. 26
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Logger waiting for messages...");

            var factory = new ConnectionFactory { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(ExchangeName, "topic");

                    var queueName = channel.QueueDeclare().QueueName;
                    channel.QueueBind(queueName, ExchangeName, "ewk.#");

                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(queueName, true, consumer);

                    int logEntry = 0;
                    Console.WriteLine("Waiting for work - press <ctrl-c> to shut down...");
                    while (true)
                    {
                        var message = consumer.Queue.Dequeue();

                        var body = message.Body;
                        var contents = Encoding.UTF8.GetString(body);

                        Console.WriteLine("[{0}:{1:yyyyMMdd-HHmmss.fffff}] {2}",
                            logEntry++, DateTimeOffset.Now, contents);
                    }
                }
            }
        }
Esempio n. 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            IConfigurationSection sec = Configuration.GetSection("MqSettings");

            services.Configure <MqSettings>(sec);
            services.AddSingleton(Configuration);

            IConnectionFactory connectionFactory;

            if (Convert.ToBoolean(Configuration.GetSection("MqSettings:IsLocal").Value))
            {
                connectionFactory = new RabbitMQ.Client.ConnectionFactory()
                {
                    UserName = Configuration.GetSection("MqSettings:UserName").Value,
                    Password = Configuration.GetSection("MqSettings:Password").Value,
                    HostName = Configuration.GetSection("MqSettings:HostName").Value,
                };
            }
            else
            {
                connectionFactory = new RabbitMQ.Client.ConnectionFactory()
                {
                    Uri = new System.Uri("amqp://*****:*****@termite.rmq.cloudamqp.com/iahqjqiq"),
                };
            }


            var connection = connectionFactory.CreateConnection();

            services.AddSingleton <IConnection>(connection);
            services.AddSingleton <IModelService, ModelService>();
            services.AddSingleton <IMqService, MqService>();
        }
        private async Task<ConnectionFactory> CreateConnectionFactoryAsync(Uri uri, CancellationToken cancellationToken)
        {
            using (await _asyncLock.WaitAsync(cancellationToken).ConfigureAwait(false))
            {
                ConnectionFactory connectionFactory;
                if (_connectionFactories.TryGetValue(uri, out connectionFactory))
                {
                    return connectionFactory;
                }
                _log.Verbose("Creating RabbitMQ connection factory to {0}", uri.Host);

                connectionFactory = new ConnectionFactory
                    {
                        Uri = uri.ToString(),
                        UseBackgroundThreadsForIO = true, // TODO: As soon as RabbitMQ supports async/await, set to false
                        TopologyRecoveryEnabled = true,
                        AutomaticRecoveryEnabled = true,
                        ClientProperties = new Dictionary<string, object>
                            {
                                { "eventflow-version", typeof(RabbitMqConnectionFactory).Assembly.GetName().Version.ToString() },
                                { "machine-name", Environment.MachineName },
                            },
                    };

                _connectionFactories.Add(uri, connectionFactory);
                return connectionFactory;
            }
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            if (args.Length < 1 || args.Length > 2)
            {
                Console.WriteLine("EasyNetQ.LogReader");
                Console.WriteLine("Usage:");
                Console.WriteLine("EasyNetQ.LogReader.exe <rabbitMqServer> [<vhost>]");
                return;
            }

            var connectionFactory = new ConnectionFactory
            {
                HostName = args[0],
                VirtualHost = args.Length == 2 ? args[1] : "/"
            };

            using (var connection = connectionFactory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(
                    logReaderQueue, // name
                    false,          // durable
                    true,           // exclusive
                    true,           // autoDelete
                    null);          // arguments

                channel.QueueBind(logReaderQueue, amqpLogExchange, "*");

                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume(logReaderQueue, false, consumer);

                Console.WriteLine("EasyNetQ.LogReader");
                Console.WriteLine("Listening to log");

                while (true)
                {
                    try
                    {
                        var e = (RabbitMQ.Client.Events.BasicDeliverEventArgs) consumer.Queue.Dequeue();
                        var logMessage = Encoding.UTF8.GetString(e.Body);

                        Console.WriteLine(logMessage);

                        channel.BasicAck(e.DeliveryTag, false);
                    }
                    catch (Exception exception)
                    {
                        // The consumer was removed, either through
                        // channel or connection closure, or through the
                        // action of IModel.BasicCancel().

                        Console.WriteLine(exception);
                        Console.WriteLine();
                        Console.WriteLine("Connection closed.");

                        break;
                    }
                }
            }
        }
        //
        // This function (call_me_from_child_constructor()) would:
        //      - extract mongodb-related parameters
        //      - prepare mongodb connection (actually the result will be "mongodb_channel")
        //
        // It must be called from child class (from response itself) after child extracts rabbitmq_parameters_bson
        // document by parsing command line. This code can not go into constructor, since we need the child to take
        // some actions prior to this code. It is not elegant, but works!
        //
        public void call_me_from_child_constructor() // when stuff for messaging is parsed from cmd line
        {
            // extract rabbitmq parameters
            //
            exchange_name = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["exchange_name"].ToJson());
            string exchange_type = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["exchange_type"].ToJson());
            ConnectionFactory conn_factory = new ConnectionFactory();
            conn_factory.HostName = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["host_name"].ToJson());
            conn_factory.UserName = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["user_name"].ToJson());
            conn_factory.Password = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["password"].ToJson());

            // extract required storage_service parameters
            //
            //string queue_name = storage_service_parameters["queue_name"];


            // create rabbitmq connection
            IConnection conn = conn_factory.CreateConnection();
            // create channel
            mongodb_channel = conn.CreateModel();

            // declare rabbitmq exchange
            mongodb_channel.ExchangeDeclare(exchange_name,
                     exchange_type,
                     false, // durable
                     false, // autodelete
                     null); // args

            mongodb_msg_props = mongodb_channel.CreateBasicProperties();
            mongodb_msg_props.ContentType = "application/json"; //  "text/plain";

        }
Esempio n. 31
0
        public static void Run()
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "logs", type: "fanout");

                var queueName = channel.QueueDeclare().QueueName;
                channel.QueueBind(queue: queueName, exchange: "logs", routingKey: "");

                Console.WriteLine(" [*] Waiting for logs.");
            
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(" [x] {0}", message);
                };
                string basicConsume = channel.BasicConsume(queue: queueName, noAck: false, consumer: consumer);
                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 32
0
        public void produceMesaage(Person person)
        {
            var connectionFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                UserName = UserName,
                Password = Password,
                HostName = HostName
            };

            var connection = connectionFactory.CreateConnection();
            var model      = connection.CreateModel();

            model.ExchangeDeclare("DemoExchange", ExchangeType.Direct);
            model.QueueDeclare("DemoQueue", true, false, false, null);
            model.QueueBind("DemoQueue", "DemoExchange", "directexchange_key");

            //publich a message



            var properties = model.CreateBasicProperties();

            properties.Persistent = false;



            byte[] messageBuffer = Encoding.Default.GetBytes(person.ID.ToString());
            Console.WriteLine(person.ID);
            model.BasicPublish("DemoExchange", "directexchange_key", properties, messageBuffer);



            Console.WriteLine("Message sent!");
        }
Esempio n. 33
0
        static void Main(string[] args)
        {
            var factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "94.131.241.80", Port = 5672, UserName = "******", Password = "******"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

                    string message = "Hello World!";
                    var    body    = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);
                    Console.WriteLine(" [x] Sent {0}", message);
                }
            }
            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
            //Console.WriteLine("Hello World!");
            //Console.WriteLine("Hello World!");
        }
Esempio n. 34
0
        public static void Receive1()
        {
            var factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    var queueDeclare = channel.QueueDeclare("hello", false, false, false, null);

                    //平衡调度,在Receiver处理并确认前一个消息之前,不会分发新的消息给Receiver
                    channel.BasicQos(0, 1, false);

                    var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);
                    consumer.Received += (sender, ea) =>
                    {
                        var message = Encoding.UTF8.GetString(ea.Body);
                        Console.WriteLine("[x] Received {0}", message);
                        channel.BasicAck(ea.DeliveryTag, false);
                    };
                    channel.BasicConsume(queueDeclare.QueueName, false, consumer);
                    Console.WriteLine("consumer启动成功,Press [enter] to exit.");
                    Console.ReadLine(); //注意不要跳出,或者会释放资源,无法自动同步
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitMqEventConsumer"/> class.
        /// </summary>
        /// <param name="connectionFactory">The connection factory.</param>
        /// <param name="exchangePath">The exchange path.</param>
        /// <param name="queue">The queue.</param>
        public RabbitMqEventConsumer(ConnectionFactory connectionFactory, string exchangePath, string queue)
        {
            _active = 1;
            _connection = connectionFactory.CreateConnection();
            _model = _connection.CreateModel();
            _queue = _model.QueueDeclare(queue, true, false, false, new Hashtable());

            // bind the queue to an exchange if specified
            if (exchangePath != null)
            {
                _model.QueueBind(_queue, exchangePath, string.Empty);
            }

            EventingBasicConsumer eventingBasicConsumer = new EventingBasicConsumer();
            eventingBasicConsumer.Received += HandleEvent;

            _model.BasicConsume(_queue, true, eventingBasicConsumer);

            #if false
            _subscription = new Subscription(_model, _queue, true);
            var thread = new Thread(ReceiveEvents);
            thread.IsBackground = true;
            thread.Name = "rabbitmq:consumer";
            thread.Start();
            #endif

            var uriBuilder = new UriBuilder(
                "rabbitmq",
                connectionFactory.HostName,
                connectionFactory.Port,
                queue);

            Uri = uriBuilder.Uri;
        }
Esempio n. 36
0
        public static void Main(string message)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "Queue1",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    var body = Encoding.Unicode.GetBytes(message);

                    channel.BasicPublish(exchange: "",
                                         routingKey: "Queue1",
                                         basicProperties: null,
                                         body: body);

                    Debug.WriteLine(" [x] Sent {0}", message);
                }
            }

        }
Esempio n. 37
0
        public static int Main(string[] args)
        {
            if (args.Length < 1) {
                Console.Error.WriteLine("Usage: Subscriber <uri> [<message count>]");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://*****:*****@host:port/vhost\"");
                return 2;
            }

            string serverAddress = args[0];
            long msgCount = (args.Length > 1) ? int.Parse(args[1]) : 10;
            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = serverAddress;
            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {
                    string queueName = ensureQueue(ch);

                    /* We'll consume msgCount message twice: once
                       using Subscription.Next() and once using the
                       IEnumerator interface.  So, we'll send out
                       2*msgCount messages. */
                    sendMessages(ch, queueName, 2*msgCount);
                    using (Subscription sub = new Subscription(ch, queueName)) {
                        blockingReceiveMessages(sub, msgCount);
                        enumeratingReceiveMessages(sub, msgCount);
                    }
                }
            }

            return 0;
        }
        public override void Test(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare("logs", "fanout");

                    var queueName = channel.QueueDeclare().QueueName;
                    //The meaning of a binding key depends on the exchange type. The fanout exchanges,
                    //which we used previously, simply ignored its value
                    channel.QueueBind(queueName, "logs", "");
                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(queueName, true, consumer);

                    Console.WriteLine("接收消息:");
                    while (true)
                    {
                        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine("Recevied:" + message);
                    }
                }
            }
        }
        public int GetMQAlarmID()
        {
            int alarmID = 0;

            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "alarm",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                    var consumer = new QueueingBasicConsumer(channel);

                    channel.BasicConsume(queue: "alarm",
                                    noAck: true,
                                    consumer: consumer);

                    var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    alarmID = Convert.ToInt32(message);
                }
            }
            return alarmID;
        }
        public static int Main(string[] args)
        {
            if (args.Length < 1) {
                Console.Error.WriteLine("Usage: ShutdownableClient <uri> [<secondsdelay>]");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://*****:*****@host:port/vhost\"");
                return 2;
            }

            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = args[0];
            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {
                    object[] callArgs = new object[1];
                    if (args.Length > 1) {
                        callArgs[0] = double.Parse(args[1]);
                    } else {
                        callArgs[0] = (double) 0.0;
                    }

                    SimpleRpcClient client = new SimpleRpcClient(ch, "ShutdownableServer");
                    client.TimeoutMilliseconds = 5000;
                    client.TimedOut += new EventHandler(TimedOutHandler);
                    client.Disconnected += new EventHandler(DisconnectedHandler);
                    object[] reply = client.Call(callArgs);
                    if (reply == null) {
                        Console.WriteLine("Timeout or disconnection.");
                    } else {
                        Console.WriteLine("Reply: {0}", reply[0]);
                    }
                }
            }
            return 0;
        }
Esempio n. 41
0
        private static void HelloWorld()
        {
            var connectionFactory = new ConnectionFactory
            {
                HostName = "localhost"
            };
            using (var connection = connectionFactory.CreateConnection())
            {
                using (IModel channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "hello",
                        durable: false,
                        exclusive: false,
                        autoDelete: false,
                        arguments: null);
                    var basicProperties = channel.CreateBasicProperties();
                    basicProperties.DeliveryMode = 2;
                    string message = "Hello World!";
                    var body = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(exchange: "",
                        routingKey: "hello",
                        basicProperties: null,
                        body: body);
                    Console.WriteLine(" [x] Sent {0}", message);
                }
            }

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
Esempio n. 42
0
        private static void WorkQueues()
        {
            var connectionFactory = new ConnectionFactory
            {
                HostName = "localhost"
            };

            using (var connection = connectionFactory.CreateConnection())
            {
                using (IModel channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "task_queue",
                                durable: true,
                                exclusive: false,
                                autoDelete: false,
                                arguments: null);

                    var message = "message...";
                    var body = Encoding.UTF8.GetBytes(message);

                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = true;
                    
                    channel.BasicPublish(exchange: "",
                                         routingKey: "task_queue",
                                         basicProperties: properties,
                                         body: body);
                    Console.WriteLine(" [x] Sent {0}", message);
                }
            }

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
Esempio n. 43
0
        //Create the connection, Model and Exchange(if one is required)
        public virtual bool ConnectToRabbitMQ()
        {
            try
            {
                Dictionary<string, Service[]> connParams = JsonConvert.DeserializeObject<Dictionary<string, Service[]>>(vcapConn);
                var connectionFactory = new ConnectionFactory();

                if (connParams.ContainsKey("rabbitmq-2.4"))
                {
                    Service s = connParams["rabbitmq-2.4"][0];

                    connectionFactory.HostName = s.Credential.Hostname;
                    connectionFactory.UserName = s.Credential.UserName;
                    connectionFactory.Password = s.Credential.Password;
                    connectionFactory.Port = s.Credential.Port;
                    connectionFactory.VirtualHost = s.Credential.VHost;
                }

                Connection = connectionFactory.CreateConnection();
                Model = Connection.CreateModel();
                bool durable = true;
                if (!String.IsNullOrEmpty(Exchange))
                    Model.ExchangeDeclare(Exchange, ExchangeTypeName, durable);
                QueueName = Model.QueueDeclare ("incidentQueue", true, false, false, null);
                Model.QueueBind(QueueName, Exchange,"");

                return true;
            }
            catch (BrokerUnreachableException e)
            {
                return false;
            }
        }
Esempio n. 44
0
        static void Main(string[] args)
        {
            var factory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //Exchange Deklare Edilir. Direct tipinde bir exchange duzenlendi.
                    channel.ExchangeDeclare(exchange: "newsheader", type: "headers");
                    //Kuyruk Deklare edilir
                    channel.QueueDeclare(queue: "newsheader_sport_news", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    channel.QueueDeclare(queue: "newsheader_all_articles", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    //X-Match in anlamı tum optionları barındırması zorunludur. all yerine any de yazılabilirdi.
                    Dictionary <string, object> newsHeader = new Dictionary <string, object>();
                    newsHeader.Add("x-match", "all");
                    newsHeader.Add("content", "news");
                    newsHeader.Add("category", "sport");

                    Dictionary <string, object> articleHeader = new Dictionary <string, object>();
                    articleHeader.Add("x-match", "all");
                    articleHeader.Add("content", "article");
                    articleHeader.Add("category", "all");

                    //ve Exchange ile İlişkilendirilir.
                    channel.QueueBind(queue: "newsheader_sport_news", exchange: "newsheader", routingKey: "", arguments: newsHeader);
                    channel.QueueBind(queue: "newsheader_all_articles", exchange: "newsheader", routingKey: "", arguments: articleHeader);

                    //BasicOptions Headerlarına atama yapılır.
                    var newsBasicOptions = channel.CreateBasicProperties();
                    newsBasicOptions.Headers = newsHeader;

                    var articleBasicOptions = channel.CreateBasicProperties();
                    articleBasicOptions.Headers = articleHeader;

                    //News icin Publish
                    for (int i = 0; i < 20; i++)
                    {
                        var message = "News " + i.ToString();
                        var body    = System.Text.Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: "newsheader", routingKey: "", basicProperties: newsBasicOptions, body: body);
                    }

                    //Article icin Publish
                    for (int i = 0; i < 20; i++)
                    {
                        var message = "Articles " + i.ToString();
                        var body    = System.Text.Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: "newsheader", routingKey: "", basicProperties: articleBasicOptions, body: body);
                    }

                    Console.WriteLine("All Messages Were Sent!");
                    Console.ReadLine();
                }
            }
        }
Esempio n. 45
0
        public async Task TestMasterLocator()
        {
            var factory = new RC.ConnectionFactory
            {
                Uri = new Uri("amqp://*****:*****@localhost:5672/")
            };
            var cf    = new CachingConnectionFactory(factory);
            var admin = new RabbitAdmin(cf);
            var queue = new AnonymousQueue();

            admin.DeclareQueue(queue);
            var client    = new HttpClient();
            var authToken = Encoding.ASCII.GetBytes("guest:guest");

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

            var result = await client.GetAsync("http://localhost:15672/api/queues/%3F/" + queue.QueueName);

            var n = 0;

            while (n++ < 100 && result.StatusCode == HttpStatusCode.NotFound)
            {
                await Task.Delay(100);

                result = await client.GetAsync("http://localhost:15672/api/queues/%2F/" + queue.QueueName);
            }

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            var content = await result.Content.ReadAsStringAsync();

            Assert.Contains("x-queue-master-locator", content);
            Assert.Contains("client-local", content);

            queue = new AnonymousQueue
            {
                MasterLocator = null
            };
            admin.DeclareQueue(queue);

            result = await client.GetAsync("http://localhost:15672/api/queues/%3F/" + queue.QueueName);

            n = 0;
            while (n++ < 100 && result.StatusCode == HttpStatusCode.NotFound)
            {
                await Task.Delay(100);

                result = await client.GetAsync("http://localhost:15672/api/queues/%2F/" + queue.QueueName);
            }

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            content = await result.Content.ReadAsStringAsync();

            Assert.DoesNotContain("x-queue-master-locator", content);
            Assert.DoesNotContain("client-local", content);
            cf.Destroy();
        }
Esempio n. 46
0
        static void Main(string[] args)
        {
            string UserName = "******";
            string Password = "******";
            string HostName = "localhost";
            //Main entry point to the RabbitMQ .NET AMQP client
            var connectionFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                UserName = UserName,
                Password = Password,
                HostName = HostName
            };
            var connection = connectionFactory.CreateConnection();
            var model      = connection.CreateModel();

            Console.WriteLine("Creating Exchange");

            // Create Exchange
            model.ExchangeDeclare("demoExchange-v1", ExchangeType.Direct);
            //model.ExchangeDeclare("demoExchange-Equalsv1", ExchangeType.Headers);

            //Create Queue in RabbitMQ
            model.QueueDeclare("demoqueue-v1", true, false, false, null);
            Console.WriteLine("Creating Queue");

            // Bind Queue to Exchange
            model.QueueBind("demoqueue-v1", "demoExchange-v1", "directexchange_key");
            Console.WriteLine("Creating Binding");

            var properties = model.CreateBasicProperties();

            properties.Persistent = false;

            var json = JsonConvert.SerializeObject(new { name = "Jhon", age = 12, DateCreate = DateTime.Now });
            var body = Encoding.UTF8.GetBytes(json);

            //byte[] messagebuffer = Encoding.Default.GetBytes("Direct Message");
            model.BasicPublish("demoExchange-v1", "directexchange_key", properties, body);

            Console.WriteLine("Message Sent");


            //Read messages
            var consumer = new EventingBasicConsumer(model);

            consumer.Received += (v, ea) =>
            {
                var body    = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received {0}", message);
            };
            //autoAck: true - delete the messages from Queue
            model.BasicConsume(queue: "demoqueue-v1", autoAck: false, consumer: consumer);

            Console.ReadLine();
        }
Esempio n. 47
0
        public IConnection CreateConnection(Configuration.ISettings configurationSettings)
        {
            RabbitMQ.Client.ConnectionFactory connectionFactory = new RabbitMQ.Client.ConnectionFactory()
            {
                HostName = configurationSettings.HostName,
                UserName = configurationSettings.UserName,
                Password = configurationSettings.Password
            };

            return(connectionFactory.CreateConnection());
        }
Esempio n. 48
0
 public MQManager(string sendQueue, string receiveQueue)
 {
     mqConnectionFactory = new RabbitMQ.Client.ConnectionFactory()
     {
         UserName    = "******",
         Password    = "******",
         VirtualHost = "/",
         HostName    = "localhost",
         Port        = 5672
     };
 }
        protected internal override void SetMonitoring()
        {
            var connectionFactory = new RabbitMQ.Client.ConnectionFactory();

            connectionFactory.Uri = new Uri(HealthCheck.EndpointOrHost);

            HealthChecksBuilder.AddRabbitMQ(provider =>
            {
                return(connectionFactory);
            }, Name, HealthStatus.Unhealthy);
        }
Esempio n. 50
-1
        public void TestWorkerReceive()
        {
            var factory = new ConnectionFactory { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare("hello", false, false, false, null);

                channel.BasicQos(0, 1, false);
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume("hello", true, consumer);

                while (true)
                {
                    var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);

                    int els = message.Split('l').Length - 1;
                    Thread.Sleep(els * 1000);

                    channel.BasicAck(ea.DeliveryTag, false);

                }
            }
        }
Esempio n. 51
-1
        static void Main()
        {
            ConnectionFactory connectionFactory = new ConnectionFactory();

            using (IConnection connection = connectionFactory.CreateConnection())
            {
                Console.Out.WriteLine("Press any key to send a message. Press `q` to quit");

                while (Console.ReadKey().ToString() != "q")
                {
                    using (IModel channel = connection.CreateModel())
                    {
                        IBasicProperties properties = channel.CreateBasicProperties();
                        #region GenerateUniqueMessageId
                        string messageId = Guid.NewGuid().ToString();

                        properties.MessageId = messageId;

                        #endregion

                        #region CreateNativePayload
                        string payload = @"<MyMessage><SomeProperty>Hello from native sender</SomeProperty></MyMessage>";
                        #endregion

                        #region SendMessage

                        channel.BasicPublish(string.Empty, "Samples.RabbitMQ.NativeIntegration", true, false, properties, Encoding.UTF8.GetBytes(payload));
                        #endregion
                        Console.Out.WriteLine("Message with id {0} sent to queue {1}", messageId, "Samples.RabbitMQ.NativeIntegration");
                    }
                }
            }
        }
Esempio n. 52
-1
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory
            {
                UserName = "******",
                Password = "******"
            };

            var exchangeName = "SignalRExchange";
            GlobalHost.DependencyResolver.UseRabbitMq(factory, exchangeName);

            var hubContext = GlobalHost.ConnectionManager.GetHubContext<Chat>();

            Task.Factory.StartNew(
                () =>
                    {
                        while (true)
                        {
                            hubContext.Clients.All.onConsoleMessage("Hello!");
                            Thread.Sleep(1000);
                        }
                    }
                );
            System.Console.WriteLine("Press any key to exit.");
            System.Console.Read();
        }
Esempio n. 53
-1
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("hello", false, false, false, null);

                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume("hello", true, consumer);

                    Console.WriteLine(" [*] Waiting for messages." +
                                             "To exit press CTRL+C");
                    while (true)
                    {
                        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received {0}", message);
                    }
                }
            }
        }
        public async Task SendAndRecieveMessage()
        {
            var queueName = "testqueueB";
            var message = new RabbitMessage() { RoutingKey = queueName, Body = new byte[]{0,1,2,3,4}};
            var messageHandler = new TestMessageHandler();

            var connectionFactory = new ConnectionFactory
                                        {
                                            HostName = "mqBalancer",
                                            UserName = "******",
                                            Password = "******",
                                            RequestedHeartbeat = 5,
                                        };

            using (var connection = new RabbitMqConnection(connectionFactory))
            {
                using (var model = new RabbitMqModel(connection))
                {
                    model.QueueDeclare(queueName, false, true, false, new Dictionary<string, object>());

                    var consumer = model.HandleMessagesAsync(queueName);
                    var publisher = new ConfirmingPublisher(model);
                    await Task.Delay(TimeSpan.FromSeconds(1));
                    publisher.Publish(string.Empty, new[] { message });
                    await consumer.ConsumeMessages(messageHandler, CancellationToken.None);
                }
            }

            var result = messageHandler.LastMessage;
            Assert.That(result.Body, Is.EquivalentTo(message.Body));
        }
        public static int Main(string[] args)
        {
            if (args.Length < 5) {
                Console.Error.WriteLine("Usage: SendString <uri> <exchange> <exchangetype> <routingkey> <message>");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://*****:*****@host:port/vhost\"");
                return 2;
            }

            string serverAddress = args[0];
            string exchange = args[1];
            string exchangeType = args[2];
            string routingKey = args[3];
            string message = args[4];

            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = serverAddress;

            using (IConnection conn = cf.CreateConnection())
                {
                    using (IModel ch = conn.CreateModel()) {

                        if (exchange != "") {
                            ch.ExchangeDeclare(exchange, exchangeType);
                        }
                        ch.BasicPublish(exchange,
                                        routingKey,
                                        null,
                                        Encoding.UTF8.GetBytes(message));
                        return 0;
                    }
                }
        }
Esempio n. 56
-1
        public RabbitMqEndpointAddress(Uri uri, ConnectionFactory connectionFactory, string name)
        {
            _uri = GetSanitizedUri(uri).Uri;

            _connectionFactory = connectionFactory;

            if (name == "*")
                name = NewId.Next().ToString("NS");

            _name = name;

            _isTransactional = uri.Query.GetValueFromQueryString("tx", false);
            _isLocal = () => DetermineIfEndpointIsLocal(uri);

            _ttl = uri.Query.GetValueFromQueryString("ttl", 0);
            _prefetch = uri.Query.GetValueFromQueryString("prefetch", (ushort)Math.Max(Environment.ProcessorCount, 10));

            bool isTemporary = uri.Query.GetValueFromQueryString("temporary", false);

            _isHighAvailable = uri.Query.GetValueFromQueryString("ha", false);
            if (_isHighAvailable && isTemporary)
                throw new RabbitMqAddressException("A highly available queue cannot be temporary");

            _durable = uri.Query.GetValueFromQueryString("durable", !isTemporary);
            _exclusive = uri.Query.GetValueFromQueryString("exclusive", isTemporary);
            _autoDelete = uri.Query.GetValueFromQueryString("autodelete", isTemporary);
        }
Esempio n. 57
-1
        /// <summary>
        /// We check for the existence of the exchange with the name <paramref name="exchangeName"/> by creating another
        /// randomly named exchange and trying to bind from the randomly named one to the one we want to check the existence of.
        /// This causes an exception if the exchange with the name <paramref name="exchangeName"/> does not exists.
        /// </summary>
        public static bool ExchangeExists(string exchangeName)
        {
            var connectionFactory = new ConnectionFactory { Uri = ConnectionString };

            using (var connection = connectionFactory.CreateConnection())
            using (var model = connection.CreateModel())
            {
                try
                {
                    const string nonExistentTopic = "6BE38CB8-089A-4B65-BA86-0801BBC064E9------DELETE-ME";
                    const string fakeExchange = "FEBC2512-CEC6-46EB-A058-37F1A9642B35------DELETE-ME";

                    model.ExchangeDeclare(fakeExchange, ExchangeType.Direct);

                    try
                    {
                        model.ExchangeBind(exchangeName, fakeExchange, nonExistentTopic);
                        model.ExchangeUnbind(exchangeName, fakeExchange, nonExistentTopic);

                        return true;
                    }
                    finally
                    {
                        model.ExchangeDelete(fakeExchange);
                    }
                }
                catch
                {
                    return false;
                }
            }
        }
Esempio n. 58
-1
        public static int Main(string[] args)
        {
            if (args.Length < 2) {
                Console.Error.WriteLine("Usage: SingleGet <uri> <queuename>");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://*****:*****@host:port/vhost\"");
                return 2;
            }

            string serverAddress = args[0];
            string queueName = args[1];
            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = serverAddress;
            IConnection conn = cf.CreateConnection();
            conn.ConnectionShutdown += new ConnectionShutdownEventHandler(LogConnClose);

            using (IModel ch = conn.CreateModel()) {
                conn.AutoClose = true;

                ch.QueueDeclare(queueName, false, false, false, null);
                BasicGetResult result = ch.BasicGet(queueName, false);
                if (result == null) {
                    Console.WriteLine("No message available.");
                } else {
                    ch.BasicAck(result.DeliveryTag, false);
                    Console.WriteLine("Message:");
                    DebugUtil.DumpProperties(result, Console.Out, 0);
                }

                return 0;
            }

            // conn will have been closed here by AutoClose above.
        }
Esempio n. 59
-1
        public static void Main()
        {
            var factory = new ConnectionFactory();
            factory.HostName = "localhost";
            using (IConnection connection = factory.CreateConnection())
            using (IModel channel = connection.CreateModel())
            {
                channel.ExchangeDeclare("logs", "fanout");

                string queue_name = channel.QueueDeclare();

                channel.QueueBind(queue_name, "logs", "");
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume(queue_name, true, consumer);

                Console.WriteLine(" [*] Waiting for logs." +
                                  "To exit press CTRL+C");
                while (true)
                {
                    var ea =
                        (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    byte[] body = ea.Body;
                    string message = System.Text.Encoding.UTF8.GetString(body);
                    Console.WriteLine(" [x] {0}", message);
                }
            }
        }
Esempio n. 60
-1
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "logs", type: "fanout");
                channel.QueueDeclare(queue: "1ToMany2",
                                                     durable: false,
                                                     exclusive: false,
                                                     autoDelete: false,
                                                     arguments: null);

                channel.QueueBind(queue: "1ToMany2",
                                  exchange: "logs",
                                  routingKey: "");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(" [x] Received {0}", message);
                };
                channel.BasicConsume(queue: "1ToMany2",
                                     noAck: true,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
        }