2.【RabbitMQ实战】- Hellow World
Producer:生产者
Consumer:消费者
RabbitMQ:中间的框是一个队列-RabbitMQ 代表使用者保留的消息缓冲区
依赖
<PackageReference Include="RabbitMQ.Client" Version="6.4.0" />
生产者代码
using RabbitMQ.Client;
using System.Reflection;
using System.Text;
using System.Threading.Channels;
namespace _01.Rabbitmq.Producer
{
public class Program
{
private static string queueName = "hello";
static void Main(string[] args)
{
// 创建一个连接工厂
ConnectionFactory factory = new ConnectionFactory
{
HostName = "localhost",
UserName = "guest",
Password = "guest",
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
/*
*生成一个队列
*1.队列名称
*2.队列里面的消息是否持久化默认消息存储在内存中
*3.该队列是否只供一个消费者进行消费是否进行共享true可以多个消费者消费
*4.是否自动删除最后一个消费者端开连接以后该队列是否自动删除true自动删除*
*5.其他参数
*/
channel.QueueDeclare("hello", false, false, false, null);//创建一个名称为hello的消息队列
for (int i = 0; i < 100; i++)
{
string message = i + "Hello World"; //控制台传递的消息内容
var body = Encoding.UTF8.GetBytes(message);
/*
* 发送一个消息
* 1.发送到那个交换机
* 2.路由的 key 是哪个
* 3.其他的参数信息
* 4.发送消息的消息体
*/
channel.BasicPublish(exchange:"", "hello", null, body); //开始传递
Console.WriteLine("已发送: {0}", message);
}
Console.ReadKey();
}
}
}
消费者代码
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
namespace _01.Rabbitmq.Consumer
{
public class Program
{
private static string queueName = "hello";
static void Main(string[] args)
{
// 创建一个连接工厂
ConnectionFactory factory = new ConnectionFactory
{
HostName = "localhost",
UserName = "guest",
Password = "guest",
};
// publisher/consumer和broker之间的TCP连接
using var connection = factory.CreateConnection();
// Channel作为轻量级的Connection极大减少了操作系统建立TCPconnection的开销
using var channel = connection.CreateModel();
// 创建队列/交换机(如队列/交换机已存在的情况可不用再次创建/此创建为:确保先开启消费者,生产者未创建队列/交换机而引发报错)
channel.QueueDeclare("hello", false, false, false, null);
// 事件对象
var consumer = new EventingBasicConsumer(channel);
/*
* 消费者消费消息
* 1.消费哪个队列
* 2.消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
* 3.消费者未成功消费的回调
*/
channel.BasicConsume("hello", false, consumer);
// 接收消息回调
consumer.Received += (sender, e) =>
{
var body = e.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("已接收: {0}", message);
};
Console.ReadKey();
}
}
}