標籤:基於 pre 取消 targe tps 記錄 demo ges 上下
前言
最近項目要使用RabbitMQ,園裡裡面已經有很多優秀的文章,Rabbitmq官網也有.net執行個體。這裡我嘗試文並茂之形式記錄下使用的過程。
安裝
RabbitMQ是建立在erlang OTP平台下,因此在windows下需要下載並安裝以下兩個組件:
1. Erlang OTP For windows
2. Rabbit MQ Windows Service Install
RabbitMQ一般還需要安裝其基於http的管理平台外掛程式,這個平台外掛程式便於我們查看和管理RabbitMQ,可以通過命令列將其啟用:
rabbitmq-plugins enable rabbitmq_management
之後就可以通過 http://localhost:15672/ 登入,帳號的密碼和密碼可以使用預設的guest/guest,登入之後的頁面:
RabbitMq 使用
就是具體的使用流程
其方框中就是Rabbitmq的message broker,我們將按上下方式來解釋:
1. 資訊發送端將訊息(message)發送到exchange
2. exchange接受訊息之後,負責將其路由到具體的隊列中
3. Bindings負責串連exchange和隊列(queue)
4. 訊息到達隊列(queue),然後等待被訊息接收端處理
5. 訊息接收端處理訊息
初始化RabbitMQ
現在我們用代碼來demo流程,首先在nuget上擷取RabbitMQ.Client:
然後建立圖中2,3,4步需要的exchange,bingding,queue
string exchangeName = "test.exchange";string queueName = "test1.queue";string otherQueueName = "test2.queue";using (IConnection conn = rabbitMqFactory.CreateConnection())using (IModel channel = conn.CreateModel()){ //2 定義一個exchange channel.ExchangeDeclare(exchangeName, "direct", durable: true, autoDelete: false, arguments: null); //4 定義兩個queue channel.QueueDeclare(queueName, durable: true, exclusive: false, autoDelete: false, arguments: null); channel.QueueDeclare(otherQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null); //3 定義exchange到queue的binding channel.QueueBind(queueName, exchangeName, routingKey: queueName); channel.QueueBind(otherQueueName, exchangeName, routingKey: otherQueueName);}
建立成功之後可以在rabbit的管理平台查看:
發送訊息
從圖上我們得知訊息是發送到rabbitmq的exchange,但可以傳一些訊息屬性如routingkey,一下代碼中我們將隊列的名字作為routingkey傳進去:
string exchangeName = "test.exchange";string queueName = "test1.queue";string otherQueueName = "test2.queue";using (IConnection conn = rabbitMqFactory.CreateConnection())using (IModel channel = conn.CreateModel()){ var props = channel.CreateBasicProperties(); props.Persistent = true; var msgBody = Encoding.UTF8.GetBytes("Hello, World!"); //1. 發送訊息到exchange ,但加上routingkey channel.BasicPublish(exchangeName, routingKey: queueName, basicProperties: props, body: msgBody); channel.BasicPublish(exchangeName, routingKey: otherQueueName, basicProperties: props, body: msgBody);}
發送之後可以在rabbitmq上看到:
接收訊息
string queueName = "test1.queue";string otherQueueName = "test2.queue";using (IConnection conn = rabbitMqFactory.CreateConnection())using (IModel channel = conn.CreateModel()){ //5. 從test1.queue 隊列擷取訊息 BasicGetResult msgResponse = channel.BasicGet(queueName, noAck: true); string msgBody = Encoding.UTF8.GetString(msgResponse.Body); //5. 從test2.queue 隊列擷取訊息 msgResponse = channel.BasicGet(otherQueueName, noAck: true); msgBody = Encoding.UTF8.GetString(msgResponse.Body);} 總結
通過以上的簡述我們對rabbitmq的使用就有了大概的瞭解。
.NET 使用 RabbitMQ 圖文簡介