1. 程式人生 > >RabbitMQ 使用demo

RabbitMQ 使用demo

chan 相同 body pro highlight tor icon ring deque

1.新建一個控制臺應用程序:如圖

技術分享

2.代碼如下:

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MQ
{
class Program
{
static void Main(string[] args)
{
string type = Console.ReadLine();
//生產者
if (type == "1")
{
ConnectionFactory factory = new ConnectionFactory();
factory.HostName = "192.168.2.24";
factory.UserName = "zhangweizhong";
factory.Password = "weizhong1988";
factory.VirtualHost = "orderqueue";
//註意host默認為5672
//factory.UserName = "admin";
//factory.Password = "123456";
//factory.VirtualHost = "adminhost";
//factory.Endpoint = new AmqpTcpEndpoint("localhost");
//默認端口
using (IConnection conn = factory.CreateConnection())
{
using (IModel channel = conn.CreateModel())
{
//在MQ上定義一個持久化隊列,如果名稱相同不會重復創建
channel.QueueDeclare("orderqueue", true, false, false, null);
while (true)
{
string message = string.Format("Message_{0}", Console.ReadLine());
byte[] buffer = Encoding.UTF8.GetBytes(message);
IBasicProperties properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2;
channel.BasicPublish("", "orderqueue", properties, buffer);
Console.WriteLine("消息發送成功:" + message);
}
}
}
}
else
{
//消費者
ConnectionFactory factory = new ConnectionFactory();
factory.HostName = "192.168.2.24";
factory.UserName = "zhangweizhong";
factory.Password = "weizhong1988";
factory.VirtualHost = "orderqueue";
using (IConnection conn = factory.CreateConnection())
{
using (IModel channel = conn.CreateModel())
{
//在MQ上定義一個持久化隊列,如果名稱相同不會重復創建
channel.QueueDeclare("orderqueue", true, false, false, null);

//輸入1,那如果接收一個消息,但是沒有應答,則客戶端不會收到下一個消息
channel.BasicQos(0, 1, false);

Console.WriteLine("Listening...");

//在隊列上定義一個消費者
QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);
//消費隊列,並設置應答模式為程序主動應答
channel.BasicConsume("orderqueue", false, consumer);

while (true)
{
//阻塞函數,獲取隊列中的消息
BasicDeliverEventArgs ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
byte[] bytes = ea.Body;
string str = Encoding.UTF8.GetString(bytes);

Console.WriteLine("隊列消息:" + str.ToString());
//回復確認
channel.BasicAck(ea.DeliveryTag, false);
}
}
}
}
}
}
}

  

踩過的坑:(備註)

1.RabbitMQ默認端口為:5672

2.引用的第三方組件:RabbitMQ.Client

需要了解RabbitMQ的安裝部署可查閱本博客RabbitMQ安裝篇章!!!

RabbitMQ 使用demo