RabbitMQ简单使用
程序员文章站
2022-06-11 22:12:57
...
RabbitMQ的介绍可以参考:
https://blog.****.net/dreamchasering/article/details/77653512
http://blog.****.net/anzhsoft/article/details/19563091
第一步下载并安装RabbitMQ服务端:
安装步骤可以参考以下文章:
https://www.cnblogs.com/ericli-ericli/p/5902270.html
第二步引用nuget包:
在:工具->NuGet包管理->程序包管理控制台,输入以下代码:
Install-Package RabbitMQ.Client
第三步编码:
class Program
{
private static ConnectionFactory rabbitMqFactory = new ConnectionFactory { HostName = "127.0.0.1", UserName = "guest", Password = "guest", VirtualHost = "/" };
const string ExchangeName = "test.exchange";
const string QueueName = "test.queue";
static void Main(string[] args)
{
//第一步是声明durable Exchange 和 Queue
using (IConnection conn = rabbitMqFactory.CreateConnection())
using (IModel channel = conn.CreateModel())
{
channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null);
channel.QueueDeclare(QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
channel.QueueBind(QueueName, ExchangeName, routingKey: QueueName);
}
//第二步就是发布持久化消息到队列
using (IConnection conn = rabbitMqFactory.CreateConnection())
using (IModel channel = conn.CreateModel())
{
var props = channel.CreateBasicProperties();
props.SetPersistent(true);
var msgBody = Encoding.UTF8.GetBytes("Hello, World!112");
channel.BasicPublish(ExchangeName, routingKey: QueueName, basicProperties: props, body: msgBody);
}
using (IConnection conn = rabbitMqFactory.CreateConnection())
using (IModel channel = conn.CreateModel())
{
//第三步就是消费消息了,有几种不同的方法从队列中消费消息,最常见的是使用BasicGet:
BasicGetResult msgResponse = channel.BasicGet(QueueName, true);
var msgBody = Encoding.UTF8.GetString(msgResponse.Body);
//NoAck: true 告诉RabbitMQ立即从队列中删除消息,另一个非常受欢迎的方式是从队列中删除已经确认接收的消息,可以通过单独调用BasicAck 进行确认:
//BasicGetResult msgResponse = channel.BasicGet(QueueName, noAck: false);
Console.WriteLine(msgBody);
}
Console.WriteLine("Hello World!");
}
}