首页 > 代码库 > RabbitMQ 使用demo
RabbitMQ 使用demo
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