public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
{
factory.setHost("49.232.202.201");
factory.setUsername("gosuncn");
factory.setPassword("123456");
factory.setVirtualHost("/gosuncn");
}
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
Map<String, Object> arguments = new HashMap<>();
arguments.put("x-message-ttl", 10000);//设置过期时间10秒
channel.queueDeclare(QUEUE_NAME, false, false, false, arguments);
channel.basicPublish("", ROUTE_KEY, true, null, MESSAGE.getBytes());
System.out.println("message delivery [" + MESSAGE + "]");
}
通过设置队列属性的方式来设置TTL
,也就是说队列中所有的消息都是有相同的TTL
属性。
也可以通过设置单条消息的方式设置:
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
builder.deliveryMode(2);
builder.expiration("6000");
AMQP.BasicProperties properties = builder.build();
channel.basicPublish("", ROUTE_KEY, true, properties, MESSAGE.getBytes());
System.out.println("message delivery [" + MESSAGE + "]");
}
设置队列
属性:一旦消息过期,就会从队列中抹去。
设置消息
属性:即使消息过期,也不会马上从队列中抹去,因为每条消息是否过期时在即将投递到消费者之前判定的。
解析:因为第一种方法里,队列中已过期的消息肯定在队列头部,RabbitMQ
只要定期从队头开始扫描是否有过期消息即可,而第二种方法里,每条消息的过期时间不同,如果要删除所有过期消息,势必要扫描整个队列,所以不如等到此消息即将被消费时再判定是否过期,如果过期,再进行删除。
- Queue TTL
queue.declare 命令中的 x-expires
参数控制 queue
被自动删除前可以处于未使用状态的时间
。
用于表示超期时间的 x-expires
参数值以微秒
为单位,并且服从和 x-message-ttl
一样的约束条件,且不能设置为 0
。
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-expires", 1800000);
channel.queueDeclare("order", false, false, false, args);