using System;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
class Program
{
static void Main(string[] args)
{
// 创建连接工厂并设置RabbitMQ服务器地址、端口等信息
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);
}
}
// 接收消息
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) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
};
// 开始消费队列中的消息
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
ConnectionFactory用于配置和建立与RabbitMQ服务器的连接。CreateConnection()和CreateModel()方法分别创建连接和通道。通道是实际执行AMQP命令的地方。QueueDeclare方法声明一个名为hello的队列。如果队列不存在,则会创建它。BasicPublish方法将消息发布到指定的队列中。EventingBasicConsumer类定义一个消费者,并注册Received事件来处理接收到的消息。BasicConsume方法开始消费队列中的消息。这段代码展示了如何使用C#与RabbitMQ进行基本的消息发送和接收操作。
上一篇:c#队列
下一篇:c# http
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站