using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
class Program
{
static void Main(string[] args)
{
// 创建连接工厂并设置参数
var factory = new ConnectionFactory() { HostName = "localhost" };
// 创建连接
using (var connection = factory.CreateConnection())
{
// 创建通道
using (var channel = connection.CreateModel())
{
// 声明队列,确保队列存在
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
// 发送消息
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
// 接收消息
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var bodyReceived = ea.Body.ToArray();
var messageReceived = Encoding.UTF8.GetString(bodyReceived);
Console.WriteLine(" [x] Received {0}", messageReceived);
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
ConnectionFactory
类创建一个连接工厂,并设置主机名为 "localhost"
,表示连接到本地的 RabbitMQ 服务器。QueueDeclare
方法声明一个名为 "hello"
的队列,确保该队列存在。如果队列已经存在,则不会重复创建。BasicPublish
方法发送到指定的队列中。EventingBasicConsumer
消费者对象,并为其注册 Received
事件处理程序,当有消息到达时触发该事件。使用 BasicConsume
方法开始消费队列中的消息。如果你需要更复杂的示例或有其他问题,请随时告诉我!
上一篇:c#字符串转日期
下一篇:c#websocket
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站