RabbitMQ 消息隊列 入門 第一章
阿新 • • 發佈:2018-05-11
cert declare host 第一章 star ESS https TP date
RabbitMQ :
官網:https://www.rabbitmq.com/
GitHub:https://github.com/rabbitmq?q=rabbitmq
第一步安裝:
- 點擊 http://www.erlang.org/downloads 下載 erlang 安裝。
- 點擊 https://www.rabbitmq.com/download.html 進入下載頁面選擇版本下載。
- 菜單查找 RabbitMQ Service - start.exe 點擊運行服務。
開始使用:
- 新建控制臺項目
- 添加引用
3.建立生產者
/// <summary> /// 消息生產者 /// </summary> /// <param name="message">消息</param> public static void RabbitProducerTest(string message) { try { //創建連接工廣場 ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost", Port = 5672, }; //實例化連接 using (var connection = factory.CreateConnection()) { //創建通道 using (var channel = connection.CreateModel()) { //聲明隊列 channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); var body = Encoding.UTF8.GetBytes(message); //消息推送 channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body); Console.WriteLine("{1} Sent {0}", message,DateTime.Now.ToString()); }//# using channel end }//# using connection end } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("HelloWordTest -- Error Press [enter] to cuntinue."); Console.ReadLine(); } } //循環發送消息 static void Main(string[] args) { while (true) { Console.WriteLine("press enter your message [enter] to send"); string message = Console.ReadLine(); RabbitMQTest.RabbitProducerTest(message); } }
4.建立消費者(新建另外一個控制臺程序)
/// <summary> /// 消息消費者 /// </summary> public static void RabbitComsumerTest() { try { ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost", Port = 5672 }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); //給通道創建消費者 var consumer = new EventingBasicConsumer(channel); //消費者事件/行為 consumer.Received += (model, ea) => { Console.WriteLine(string.Format("{0} Received a message", DateTime.Now.ToString())); var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine("Message Content:{0}", message); }; channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer); Console.ReadLine(); } } }catch(Exception ex) { Console.WriteLine("發生異常:"+ex.Message); Console.ReadLine(); } } static void Main(string[] args) { RabbitMQTest.RabbitComsumerTest(); }
5.同時運行兩個程序
如果隊列堆積,可開啟多個消費者增加處理效率
RabbitMQ 消息隊列 入門 第一章