RabbitMQ :
官网:https://www.rabbitmq.com/
GitHub:https://github.com/rabbitmq?q=rabbitmq
第一步安装:
- 点击 http://www.erlang.org/downloads 下载 erlang 安装。
- 点击 https://www.rabbitmq.com/download.html 进入下载页面选择版本下载。
- 菜单查找 RabbitMQ Service - start.exe 点击运行服务。
开始使用:
- 新建控制台项目
- 添加引用
3.建立生产者
/// <summary>
/// 消息生产者
/// </summary>
/// <param name="message">消息</param>
public static void RabbitProducerTest(string message)
{
try
{
//创建连接工广场
ConnectionFactory factory = new ConnectionFactory()
{
HostName = "localhost",
Port = 5672,
};
//实例化连接
using (var connection = factory.CreateConnection())
{
//创建通道
using (var channel = connection.CreateModel())
{
//声明队列
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var body = Encoding.UTF8.GetBytes(message);
//消息推送
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine("{1} Sent {0}", message,DateTime.Now.ToString());
}//# using channel end
}//# using connection end
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("HelloWordTest -- Error Press [enter] to cuntinue.");
Console.ReadLine();
}
}
//循环发送消息
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("press enter your message [enter] to send");
string message = Console.ReadLine();
RabbitMQTest.RabbitProducerTest(message);
}
}
4.建立消费者(新建另外一个控制台程序)
/// <summary>
/// 消息消费者
/// </summary>
public static void RabbitComsumerTest()
{
try
{
ConnectionFactory factory = new ConnectionFactory()
{
HostName = "localhost",
Port = 5672
};
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
//给通道创建消费者
var consumer = new EventingBasicConsumer(channel);
//消费者事件/行为
consumer.Received += (model, ea) =>
{
Console.WriteLine(string.Format("{0} Received a message", DateTime.Now.ToString()));
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("Message Content:{0}", message);
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.ReadLine();
}
}
}catch(Exception ex)
{
Console.WriteLine("发生异常:"+ex.Message);
Console.ReadLine();
}
}
static void Main(string[] args)
{
RabbitMQTest.RabbitComsumerTest();
}
5.同时运行两个程序
如果队列堆积,可开启多个消费者增加处理效率