我們在RabbitMQ中發布消息時,在代碼中有兩種方法設置某個隊列的消息過期時間:
1、針對隊列來說,可以使用x-message-ttl參數設置當前隊列中所有消息的過期時間,即當前隊列中所有的消息過期時間都一樣;
2、針對單個消息來說,在發布消息時,可以使用Expiration參數來設置單個消息的過期時間。
以上兩個參數的單位都是毫秒,即1000毫秒為1秒。如果以上兩個都設置,則以當前消息最短的那個過期時間為准。
接下來讓我們在在代碼中相見!
針對隊列來說:
//首先創建一個連接工廠對象 var factory = new ConnectionFactory() { HostName = "localhost", UserName = "yyt", Password = "yyt888888",VirtualHost="log" }; //然后使用工廠對象創建一個TCP連接 using (var connection = factory.CreateConnection()){ //在當前連接上創建一根通信的虛擬管道 using (var channel = connection.CreateModel()) { //聲明一個交換機 channel.ExchangeDeclare("e.log", "direct"); //聲明一個隊列,設置arguments的參數x-message-ttl為10000毫秒 channel.QueueDeclare(queue: "q.log.error", durable: false, exclusive: false, autoDelete: false, arguments: new Dictionary<string, object> { { "x-message-ttl",10000} //x-message-ttl即設置當前隊列消息的過期時間。ttl即為time to live }); channel.QueueBind("q.log.error", //隊列名稱 "e.log", //交換機名稱 "log.error"); //自定義的RoutingKey var body = Encoding.UTF8.GetBytes("測試消息"); var properties = channel.CreateBasicProperties(); //設置消息持久化 properties.SetPersistent(true); //發布消息 channel.BasicPublish(exchange: "e.log", routingKey: "log.error", basicProperties: properties, body: body); } }
針對的單個消息來說:
//首先創建一個連接工廠對象 var factory = new ConnectionFactory() { HostName = "localhost", UserName = "yyt", Password = "yyt888888",VirtualHost="log" }; //然后使用工廠對象創建一個TCP連接 using (var connection = factory.CreateConnection()){ //在當前連接上創建一根通信的虛擬管道 using (var channel = connection.CreateModel()) { //聲明一個交換機 channel.ExchangeDeclare("e.log", "direct"); //聲明一個隊列,設置arguments的參數x-message-ttl為10000毫秒 channel.QueueDeclare(queue: "q.log.error", durable: false, exclusive: false, autoDelete: false, arguments: new Dictionary<string, object> { //{ "x-message-ttl",10000} //x-message-ttl即設置當前隊列消息的過期時間。ttl即為time to live }); channel.QueueBind("q.log.error", //隊列名稱 "e.log", //交換機名稱 "log.error"); //自定義的RoutingKey var body = Encoding.UTF8.GetBytes("測試消息"); var properties = channel.CreateBasicProperties(); //設置消息持久化 properties.SetPersistent(true); //設置當個消息的過期時間為5000毫秒 properties.Expiration = "5000"; channel.BasicPublish(exchange: "e.log", routingKey: "log.error", basicProperties: properties, body: body); } }
參考信息:https://www.rabbitmq.com/ttl.html
