rabbitmq
定义交换机
var exchangeName = "delay-exchange";
//设置Exchange队列类型
var argMaps = new Dictionary<string, object>()
{
{"x-delayed-type", "direct"}
};
channel.ExchangeDeclare(exchange: exchangeName,
type: "x-delayed-message",
durable: true,
autoDelete: false,
arguments: argMaps);
注意,这里通过x-delayed-type指定交换机的基础类型,也就是direct,topic,fanout,header
定义队列及绑定队列
channel.QueueDeclare(queue: "QueueName",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
channel.QueueBind("QueueName",
exchange: exchangeName,
routingKey: "routingKey");
发布消息
var props = channel.CreateBasicProperties();
//设置消息的延迟时间
props.Headers = new Dictionary<string, object>()
{
{ "x-delay", publishMessage.DelayMs.Value }
};
channel.BasicPublish(exchange: exchangeName,
routingKey: "QueueName",
basicProperties: props,
body: body);
注意,这里通过x-delay指定消息的从交换机到队列的延迟时间,也就是期望的延迟时间