public Telegraph() { var connectionFactory = new ConnectionFactory { HostName = "localhost", VirtualHost = "test" }; _connection = connectionFactory.CreateConnection(); _channel = _connection.CreateModel(); _consumer = new QueueingBasicConsumer(_channel); }
public static void Main() { //get the config data GetConfig(); //connect to rabbitmq Console.WriteLine("Connecting . . ."); var factory = new ConnectionFactory(); factory.HostName = _brokerEndpoint; factory.UserName = _brokerUser; factory.Password = _brokerPassword; factory.VirtualHost = "/"; //assumes we use the default vhost factory.Protocol = Protocols.DefaultProtocol; //assumes we use the default protocol factory.Port = AmqpTcpEndpoint.UseDefaultPort; //assumes we use the default port IConnection conn = factory.CreateConnection(); using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { //tell rabbitmq to send confirmation when messages are successfully published channel.ConfirmSelect(); channel.WaitForConfirmsOrDie(); Console.WriteLine("Connected to " + _brokerEndpoint); Console.WriteLine(" [*] Ready to send messages." + "To exit press CTRL+C"); while(true) { //loop for user to supply messages ProcessMessages(channel); } } } }
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!"); }
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(); }
} // 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
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(); //注意不要跳出,或者会释放资源,无法自动同步 } } }
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"); } }
/// <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; }
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 ); } } }
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)); }
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()); }
//https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/NewTask/NewTask.cs static void Enqueue(string queueName, string hostName, string msg, int cycles) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); var factory = new ConnectionFactory() { HostName = hostName }; factory.UserName = "******"; factory.Password = "******"; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { byte[] body; QueueDeclareOk res = channel.QueueDeclare(queueName, true, false, false, null); if (msg != null) body = Encoding.UTF8.GetBytes(msg); else body = new byte[0]; var properties = channel.CreateBasicProperties(); properties.SetPersistent(true); sw.Start(); for (int n = 0; n < cycles; ++n) { channel.BasicPublish("", queueName, properties, body); } sw.Stop(); } } Console.WriteLine(" [x] Enqueue {0} with count = {1}, time = {2} ms", "", cycles, sw.ElapsedMilliseconds); }
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"); }
public void NewTask() { string filepath = Utils.GetFullPathFileName("Chegou.png"); byte[] body = Utils.GetFileAsBytesOrNull (filepath); var factory = new ConnectionFactory() { HostName = "diablo" }; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { //channel.QueueDeclare("Work_Queue"); // version shup channel.QueueDeclare("Work_Queue",true,false,false,null); var properties = channel.CreateBasicProperties(); properties.SetPersistent(true); channel.BasicPublish(exchange: "", routingKey: "Work_Queue", basicProperties: properties, body: body); Text text ,log; text = GameObject.Find("TextPE").GetComponent<Text>(); int count = int.Parse(text.text) + 1; text.text= count.ToString(); log = GameObject.Find("console").GetComponent<Text>(); var fileInfo = new System.IO.FileInfo("Chegou.png"); var fileSize = (fileInfo.Length/1024f)/1024f; log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Mensagem Enviada Work Queue : " + fileSize.ToString("0.00") + " MB" + "\n"; connection.Close(); //Console.WriteLine(" [x] Sent {0}", message); } }
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(); //注意不要跳出,或者会释放资源,无法自动同步 } } }
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 SendPSMessage() { string filepath = Utils.GetFullPathFileName("Chegou.png"); byte[] messageBytes = Utils.GetFileAsBytesOrNull (filepath); var factory = new ConnectionFactory() { HostName = "diablo" , UserName = "******" , Password = "******"}; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "publishSubEX", type: "fanout"); var body = messageBytes; //var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "publishSubEX", routingKey: "", basicProperties: null, body: body); Text text ,log; text = GameObject.Find("TextPE").GetComponent<Text>(); int count = int.Parse(text.text) + 1; text.text= count.ToString(); log = GameObject.Find("console").GetComponent<Text>(); var fileInfo = new System.IO.FileInfo("Chegou.png"); var fileSize = (fileInfo.Length/1024f)/1024f; log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Mensagem Enviada Publish / Subscribe : " + fileSize.ToString("0.00") + " MB" + "\n"; } }
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]); }
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..."); }
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(); }
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; }; }
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(); } } }
public void Worker() { Text log = GameObject.Find("console").GetComponent<Text>(); var factory = new ConnectionFactory() { HostName = "diablo", UserName = "******" ,Password = "******"}; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); 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); /// int dots = message.Split('.').Length - 1; // Thread.Sleep(1000); log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] recebendo mensagens. \n"; channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: "Work_Queue", noAck: false, consumer: consumer); } }
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(); }
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(); } } }
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(); }
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 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(); }
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); } } } }
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"); }
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!"); }
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); } } } }
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(); } } } }
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(); } }
//https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/Worker/Worker.cs static void Dequeue(string queueName, string hostName, int expected) { int count = 0; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); var factory = new ConnectionFactory() { HostName = hostName }; factory.UserName = "******"; factory.Password = "******"; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare(queueName, true, false, false, null); channel.BasicQos(0, 1, false); var consumer = new QueueingBasicConsumer(channel); channel.BasicConsume(queueName, false, consumer); sw.Start(); while (count < expected) { BasicDeliverEventArgs ea = consumer.Queue.Dequeue(); var body = ea.Body; var message = Encoding.UTF8.GetString(body); channel.BasicAck(ea.DeliveryTag, false); ++count; } sw.Stop(); } } Console.WriteLine(" [x] {0} messages dequeued in time = {1} ms", count, sw.ElapsedMilliseconds); }
public void SendSimpleQueue() { string filepath = Utils.GetFullPathFileName("rabbit.ogg"); byte[] body = Utils.GetFileAsBytesOrNull (filepath); var factory = new ConnectionFactory() { HostName = "diablo" ,UserName = "******" ,Password = "******" }; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { //channel.QueueDeclare("SimpleQueue"); //version shup channel.QueueDeclare("SimpleQueue",true,false,false,null); // string message = "Hello World!"; //var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: "SimpleQueue", basicProperties: null, body: body); Text text ,log; text = GameObject.Find("TextPE").GetComponent<Text>(); int count = int.Parse(text.text) + 1; text.text= count.ToString(); log = GameObject.Find("console").GetComponent<Text>(); var fileInfo = new System.IO.FileInfo("rabbit.ogg"); var fileSize = (fileInfo.Length/1024f)/1024f; log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Mensagem Enviada SingleQueue : " + fileSize.ToString("0.00") + " MB" + "\n"; connection.Close(); } }
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; }
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(); }
public void ConsumeSimpleQueue() { var factory = new ConnectionFactory() { HostName = "diablo" ,UserName = "******" ,Password = "******" }; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { //channel.QueueDeclare("SimpleQueue"); //version shup channel.QueueDeclare("SimpleQueue",true,false,false,null); BasicGetResult result = channel.BasicGet("SimpleQueue", true); while (result != null) { //string message = result.Body; Utils.SaveFileToDisk("rabbitVideo.ogg",result.Body); result = channel.BasicGet("SimpleQueue", true); var fileInfo = new System.IO.FileInfo("rabbitVideo.ogg"); var fileSize = (fileInfo.Length/1024f)/1024f; Atualiza(fileSize.ToString("0.00") + " MB"); } if(result == null){ Text log; log = GameObject.Find("console").GetComponent<Text>(); log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Não Há mensagens para consumir \n"; connection.Close(); } } }
//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; } }
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(); }
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); } } }
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; }
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; } } } }
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(); } } }
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(); }
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()); }
/// <summary> /// Bağlantı kontrolünü yapar. /// </summary> /// <returns></returns> private bool RabbitMqConnectionState() { RabbitMQ.Client.ConnectionFactory factory = new RabbitMQ.Client.ConnectionFactory(); factory.UserName = _rabbitMqUserName; factory.Password = _rabbitMqPassword; factory.VirtualHost = "/"; factory.HostName = _mqOnServer; _connection = factory.CreateConnection(); return(_connection.IsOpen); }
private void InitializeConnection() { mqConnectionFactory = new RabbitMQ.Client.ConnectionFactory() { UserName = userName, Password = password, VirtualHost = virtualHost, HostName = hostName, Port = port }; mqConnection = mqConnectionFactory.CreateConnection(); channel = mqConnection.CreateModel(); }
private void SetupRabbitMq() { var connectionfactory = new RabbitMQ.Client.ConnectionFactory() { Password = Password, UserName = UserName, HostName = HostName }; var connection = connectionfactory.CreateConnection(); model = connection.CreateModel(); }
/// <summary> /// Create conection to RabbitMq. /// </summary> /// <param name="hostName">RabbitMq host name</param> /// <param name="queueName">Queue name </param> /// <param name="socketReadTimeout">Timeout setting for socket read operations (in milliseconds).</param> /// <param name="socketWriteTimeout">Timeout setting for socket write operations (in milliseconds).</param> /// <returns></returns> public static IConnection CreateConection(string hostName, int socketReadTimeout = 30000, int socketWriteTimeout = 30000) { var factory = new RabbitMQ.Client.ConnectionFactory() { HostName = hostName, SocketReadTimeout = socketReadTimeout, SocketWriteTimeout = socketWriteTimeout }; var connection = factory.CreateConnection(); return(connection); }
public static IConnection GetConnection() { var connectionFactory = new RabbitMQ.Client.ConnectionFactory() { HostName = "localhost", Port = AmqpTcpEndpoint.UseDefaultPort, Protocol = Protocols.DefaultProtocol, VirtualHost = "/", UserName = "******", Password = "******" }; return(connectionFactory.CreateConnection()); }
public RabbitMQClient() { var connectionFactory = new RabbitMQ.Client.ConnectionFactory() { UserName = "******", Password = "******", HostName = "rabbitmq" }; this.connection = connectionFactory.CreateConnection(); this.channel = connection.CreateModel(); channel.QueueDeclare(queueRequest, false, false, false, null); channel.QueueDeclare(queueResult, false, false, false, null); }
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); } } }
/// <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; } } }
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. }
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"); } } } }
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(); } }
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; } } }
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); } } }