原文:第五节 RabbitMQ在C#端的应用-消息收发
版权声明:未经本人同意,不得转载该文章,谢谢 https://blog.csdn.net/phocus1/article/details/87361905 </div>
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
<div class="htmledit_views" id="content_views">
<p><strong>1.VS2013创建生产者端</strong></p>
创建控制台程序:WIRabbitMQProducer,并将.net框架修改为4.6.2(版本4.6以上都可以)。
添加NuGet程序包,RabbitMQ.Client,编写生产者程序,代码如下:
class Program
{
static void Main(string[] args)
{
IConnection conn = null;
IModel channel = null;
try
{
ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", Port = 5672, UserName = "wiadmin", Password = "wi2019" };
using (conn = factory.CreateConnection())
{
using (channel = conn.CreateModel())
{
string queueName = "mqQueueName1";//队列名称
channel.QueueDeclare(queueName, false, false, false, null);//定义队列
string message = "消息内容201902191355";//消息内容
var properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2;//持久化
for (int i = 0; i < 1900000; i++)
{
string strSendMsg = string.Format("{0}_{1}", message, i);
var body = Encoding.UTF8.GetBytes(strSendMsg);
channel.BasicPublish("", queueName, properties, body);//推送
Console.WriteLine("已生产:{0}", strSendMsg);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("异常", ex.ToString());
}
finally
{//关闭
conn.Close();
channel.Close();
}
}
}
运行效果:
2.VS2013创建消费者端
创建控制台程序:WIRabbitMQConsumer,并将.net框架修改为4.6.2。
添加NuGet程序包,RabbitMQ.Client,编写生产者程序,代码如下:
public void SubscribeMQ()
{
IConnection conn = null;
IModel channel = null;
int runIndex = 1;
try
{
Console.Write("------启动RabbitMQ监听-------
");
ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", Port = 5672, UserName = "wiadmin", Password = "wi2019" };
using (conn = factory.CreateConnection())
{
using (channel = conn.CreateModel())
{
#region 消息响应
string queueName = "mqQueueName1";
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(queueName, false, consumer);
while (true)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("已接收:{0},{1}", message, runIndex);
runIndex++;
channel.BasicAck(ea.DeliveryTag, false);
}
#endregion
}
}
}
catch (Exception ex)
{
}
}
运行效果:
可同时运行多个消费者端,实现多端同时消费,提交处理效率: