需要创建两个控制台应用
引用用下面的包
(1)生产者
static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory(); factory.HostName="192.168.10.10";(例)(填自己连接MQ使用的端口就行) factory.UserName="admin"; factory.Password="aq2017"; string type = Console.ReadLine(); //输入1创建一个生产者 发送消息 if (type == "1") { using (IConnection conn = factory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { //在MQ上定义一个持久化队列,如果名称相同不会重复创建 channel.QueueDeclare("MyRabbitMQ", true, false, false, null); while (true) { string message = string.Format("ffff:{0}", Console.ReadLine()); byte[] buffer = Encoding.UTF8.GetBytes(message); IBasicProperties properties = channel.CreateBasicProperties(); properties.DeliveryMode = 2; channel.BasicPublish("", "MyRabbitMQ", properties, buffer); Console.WriteLine("消息发送成功:" + message); } } } } }
(2)消费者
static void Main(string[] args) { //消费者 ConnectionFactory factory = new ConnectionFactory(); factory.HostName = "192.168.10.10"; factory.UserName = "admin"; factory.Password = "aq2017"; using (IConnection conn = factory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { //在MQ上定义一个持久化队列,如果名称相同不会重复创建 channel.QueueDeclare("MyRabbitMQ", true, false, false, null); //输入1,那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息 channel.BasicQos(0, 1, false); Console.WriteLine("Listening..."); //在队列上定义一个消费者 QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel); //消费队列,并设置应答模式为程序主动应答 channel.BasicConsume("MyRabbitMQ", 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); } } } }
运行两个控制台