Amqp.net C#客户端连接服务器,收发消息
时间: 2024-11-27 09:19:11 浏览: 3
AMQP (Advanced Message Queuing Protocol) 是一种开放标准的消息队列协议,用于分布式系统间的通信。在 .NET 平台上,你可以使用 `AmqpNetLite` 库来创建 C# 客户端,它提供了一套简单易用的 API 来连接 RabbitMQ、Azure Service Bus 等支持 AMQP 的消息队列服务。
以下是基本步骤:
1. **添加依赖**:如果你使用的是 NuGet,可以在项目中添加 `AmqpNetLite` 和 `MassTransit`(如果需要高级功能如异步处理和错误恢复)的引用。
```bash
Install-Package AmqpNetLite
Install-Package MassTransit.Amqp
```
2. **创建连接**:
```csharp
using RabbitMQ.Client;
var connectionFactory = new ConnectionFactory() { HostName = "your.rabbitmq.host", UserName = "your_username", Password = "your_password" };
IConnection connection = connectionFactory.CreateConnection();
IModel channel = connection.CreateModel();
```
3. **发送消息**:
```csharp
string exchangeName = "your_exchange";
string routingKey = "your_routing_key";
byte[] messageBody = Encoding.UTF8.GetBytes("Your message body");
channel.BasicPublish(exchangeName, routingKey, null, messageBody);
```
4. **接收消息**:
```csharp
queueName = "your_queue";
BasicConsumer consumer = new BasicConsumer(channel);
channel.BasicConsume(queueName, true, consumer, null);
while (true)
{
BasicDeliverEventArgs args = await consumer.QueueReceiveAsync();
string receivedMessage = Encoding.UTF8.GetString(args.Body);
// Process the received message here
}
```
5. **关闭连接**:
```csharp
channel.Dispose();
connection.Close();
```
阅读全文