RabbitMQ 官网
一个生产者,一个消费者
● 消息产生者将消息放入队列
● 消息的消费者监听消息队列,如果队列中有消息就消费掉
● 消息被拿走后,自动从队列中删除
1、简单队列--生产者
using RabbitMQ.Client;
using System;
using System.Text;
namespace SimpleSendConsole
{
class Program
{
/// <summary>
/// 简单队列--生产者
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
///队列名称
string queueName = "queue1";
///1.创建连接工厂
ConnectionFactory factory = new ConnectionFactory
{
HostName = "127.0.0.1",//rabbitmq ip
Port = 5672,//端口号
UserName = "guest",//用户名
Password = "guest",//密码
//VirtualHost="/tj"//虚拟主机
};
///2.创建连接对象
using (IConnection connection = factory.CreateConnection())
{
///3.创建连接会话对象,信道
using (IModel channel = connection.CreateModel())
{
///4.声明一个队列,绑定队列
channel.QueueDeclare(
queue: queueName,//队列名称
durable: false,//持久化
exclusive: false,//排他队列
autoDelete: false,//队列自动删除
arguments: null);
for (int i = 0; i < 20; i++)
{
///消息内容
string message = $"Hello World {i} !!!";
///5.发送消息
channel.BasicPublish(exchange: "", routingKey: queueName, basicProperties: null, body: Encoding.UTF8.GetBytes(message));
Console.WriteLine(" [x] Sent {0}", message);
}
}
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
2、简单队列--消费者
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
namespace SimpleReceiveConsole
{
class Program
{
/// <summary>
/// 简单队列--消费者
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
///队列名称
string queueName = "queue1";
///1. 创建连接工厂
ConnectionFactory factory = new ConnectionFactory
{
HostName = "127.0.0.1",
Port = 5672,//端口号
UserName = "guest",//用户名
Password = "guest",//密码
//VirtualHost = "/tj"
};
///2. 创建连接对象
using (var connection = factory.CreateConnection())
{
///3. 创建连接会话对象
using (var channel = connection.CreateModel())
{
///4. 声明一个队列,绑定队列
channel.QueueDeclare(
queue: queueName,//消息队列名称
durable: false,//持久化
exclusive: false,//排他队列
autoDelete: false,//自动删除
arguments: null);
///事件基本消费者
EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
///接收到消息事件
consumer.Received += (model, ea) =>
{
///打印消息
Console.WriteLine(" [x] Received {0}", Encoding.UTF8.GetString(ea.Body.ToArray()));
};
///消费消息
channel.BasicConsume(
queueName, //队列名称
true, //自动确认
consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
}
*
*
*