RabbitMQ 教程(二)本地數據交互

1、部署好RabbitMQ環境後,咱們能夠來簡單寫代碼調用。建立兩個Console程序,分別命名爲:RabbitMQ.Server、RabbitMQ.Clientapi

(1)netFreamework須要4.5及以上版本,而且項目中要引用 RabbitMQ.Client.dll,RabbitMQ.ServiceModel.dlltcp

如須要dll的,能夠到此下載(請支持下,謝謝):http://download.csdn.net/download/zmoneyz/9980207spa

 

(2)RabbitMQ.Server,負責發送信息,爲方便理解,HostName就直接使用了localhost.net

var factory = new RabbitMQ.Client.ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())//建立Socket鏈接
{
    using (var channel = connection.CreateModel())//channel中包含幾乎全部的api操做queue
    {
        //參數含義:隊列名、是否持久化、排它性、是否自動刪除
        channel.QueueDeclare(queue: "AllenLeeQueue",//隊列名
                             durable: false,//是否持久化
                             exclusive: false,//排它性
                             autoDelete: false,//是否自動刪除,一旦客戶端鏈接斷開則自動刪除queue
                             arguments: null);////若是安裝了隊列優先級插件則能夠設置優先級

        string message = "This morning i want to play Dota.....";
        var body = Encoding.UTF8.GetBytes(message);

        channel.BasicPublish("", "AllenLeeQueue", null, body);
        Console.WriteLine("AllenLee Sent Msg: {0}", message);
    }
}

Console.WriteLine(" Press 【Enter】 to exit.");
Console.ReadLine();

 

(3)RabbitMQ.Client,負責接收信息,HostName也爲localhost插件

var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
     channel.QueueDeclare(
     queue: "AllenLeeQueue",//指定發送消息的queue,和生產者queue匹配
     durable: false,
     exclusive: false,
     autoDelete: false,
     arguments: null
     );

     var consumer = new EventingBasicConsumer(channel);

     string strMsg = "";
     //註冊接收事件,一旦建立鏈接就去拉取消息
     consumer.Received += (model, ea) =>
     {
         var body = ea.Body;
         var message = Encoding.UTF8.GetString(body);
         strMsg = message;
         Console.WriteLine("AllenLee Received: {0}", message);
     };

     channel.BasicConsume(
         queue: "AllenLeeQueue",
         noAck: true,//和tcp協議的ack同樣,爲false則服務端必須在收到客戶端的回執(ack)後才能刪除本條消息
         consumer: consumer
     );

     Console.WriteLine(" Press 【Enter】 to exit.");
     Console.ReadLine();
} 

 

(4)運行RabbitMQ.Server,RabbitMQ.Clientcode

這兩個沒有必然的前後執行順序,由於Client會一直要偵聽檢測服務端發來的信息,當Server端一旦有信息傳來,Client就能夠立刻Get到,下圖是我先運行Client再運行Server的狀況blog

 

(5)固然,也能夠把一些通用變量往前提,看你我的愛好隊列

private static ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost" };至此,咱們已經完成簡單的 RabbitMQ 的使用,後續咱們繼續往深刻探討,歡迎你們多提寶貴意見,謝謝!
相關文章
相關標籤/搜索