using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
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.ExchangeDeclare(“dead-letter-exchange”, ExchangeType.Direct);
// 定义死信队列
var deadLetterQueueArgs=new Dictionary<string, object>
{
{ “x-dead-letter-exchange”, “dead-letter-exchange” },
{ “x-message-ttl”, 60000 } // 消息超时时间设置为60秒
};
channel.QueueDeclare(“dead-letter-queue”, true, false, false, deadLetterQueueArgs);
// 定义队列
var queueName=”my-queue”;
channel.QueueDeclare(queueName, true, false, false, null);
// 将队列绑定到死信交换机上
channel.QueueBind(queueName, “dead-letter-exchange”, “my-routing-key”);
// 定义消息消费者
var consumer=new EventingBasicConsumer(channel);
consumer.Received +=(model, ea)=>
{
var body=ea.Body;
var message=Encoding.UTF8.GetString(body.ToArray());
Console.WriteLine($”接收到消息:{message}”);
};
channel.BasicConsume(queueName, true, consumer);
// 发送消息
var message=”Hello RabbitMQ!”;
var body=Encoding.UTF8.GetBytes(message);
var properties=channel.CreateBasicProperties();
properties.Persistent=true;
properties.Expiration=”5000″; // 消息过期时间设置为5秒
channel.BasicPublish(“”, queueName, properties, body);
Console.WriteLine(“按任意键退出。”);
Console.ReadKey();
}
}
}
}