参考链接 :https://blog.csdn.net/zhulongxi/article/details/72867545
https://www.cnblogs.com/ericli-ericli/p/5917018.html
1.新建RabbitMQTest解决方案,包含producer生产者和consumer消费者两个工程
2、添加RabbitMQ.Client引用
在项目的引用上右键选择管理nuget程序包,搜索RabbitMQ.Client.dll,然后安装,因为最新的需要Framework4.5以上,所以如果是4.0的Framework的话需要修改成高版本的
3、producer工程下的代码
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace RabbitMQTest
{
class Program
{
static void Main(string[] args)
{
var factory = new ConnectionFactory();
factory.HostName = "localhost";
factory.UserName = "zka";
factory.Password = ""; using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("hello", false, false, false, null);
string message = "Hello World";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("", "hello", null, body);
Console.WriteLine(" set {0}", message);
}
}
}
}
}
4、consumer代码
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Consumer
{
class Program
{
static void Main(string[] args)
{
var factory = new ConnectionFactory();
factory.HostName = "localhost";
factory.UserName = "zka";
factory.Password = ""; using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("hello", false, false, false, null); var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("hello", true, consumer); Console.WriteLine(" waiting for message.");
while (true)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("Received {0}", message); }
}
}
}
}
}
5、将producer设置为启动项,先运行生产者,屏幕一闪退出了,然后查看RabbitMQ Management页面的Queues选项http://localhost:15672/#/queues,看到如下图,队列中已经收到一个消息
可以多运行几次producer,可以看到每运行一次,消息队列里的消息数量就会加1,如下图运行了5次producer
6、然后将consumer项目设置为启动项,运行,如下图所示,打印出来5次,并且持续监控消息队列
此时,消息队列中的消息又变为了0,如下图
7、可能出现的问题及解决办法
执行时VS报错:
“RabbitMQ.Client.Exceptions.BrokerUnreachableException”类型的未经处理的异常在 RabbitMQ.Client.dll 中发生 其他信息: None of the specified endpoints were reachable。
进入查看详细的内部异常:
innerEception:{"The AMQP operation was interrupted: AMQP close-reason, initiated by Peer, code=530, text=\"NOT_ALLOWED - access to vhost '/' refused for user 'eric'\", classId=10, methodId=40, cause="}
此时,我们打开在http://localhost:15672/#/users 可以看到eric 下 的Can access virtual hosts 为 NoAccess
解决办法:
rabbitmqctl控制台输入
rabbitmqctl set_permissions -p / userName "." "." ".*"
再次执行时,可以看到: