springboot集成RabbitMQ TTL特性
说明:
- TTL 全称 Time To Live(存活时间/过期时间), 当消息到达存活时间后,还没有被消费,会被自动清除。
- RabbitMQ可以对单个消息设置过期时间,也可以对整个队列(Queue)设置过期时间。
- 设置队列过期时间使用参数:x-message-ttl,单位:ms(毫秒),会对整个队列消息统一过期。
- 设置单个消息过期时间使用参数:expiration。单位:ms(毫秒),当该消息在队列头部时(消费时),会单独判断这一消息是否过期。
- 如果两者都进行了设置,以时间短的为准。
1. 编写RabbitMQ配置类, 定义队列的过期时间
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class RabbitMQConfig {
public static final String TTL_QUEUE = "springboot_ttl_queue"; // 测试RabbitMQTTL
public static final String TTL_EXCHANGE = "springboot_ttl_exchange";
// 1. 定义交换机
@Bean("TtlExchange")
public Exchange ttlExchange(){
return ExchangeBuilder.topicExchange(TTL_EXCHANGE).durable(true).build();
}
// 2. 定义队列
@Bean("TtlQueue")
public Queue ttlQueue(){
// 设置队列过期时间
Map<String, Object> arguments = new HashMap<>();
arguments.put("x-message-ttl",100000);
return QueueBuilder.durable(TTL_QUEUE).withArguments(arguments).build();
}
// 3. 绑定交换机与队列
@Bean
public Binding ttlBindQueueConfirmAndExchange(@Qualifier("TtlQueue") Queue ttlQueue,@Qualifier("TtlExchange") Exchange ttlExchange){
return BindingBuilder.bind(ttlQueue).to(ttlExchange).with("qos.#").noargs();
}
}
2. 编写测试类, 发送消息
import com.itheima.rabbitmqConfig.RabbitMQConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* TTL: Time To Live(存活时间/过期时间)
* 当消息到达存活时间后,还没有被消费,会被自动清除
*/
@Test
public void ttlTest(){
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend(RabbitMQConfig.TTL_EXCHANGE,"qos.test","Test RabbitMQ TTL success!");
}
}
/**
* 测试当前发送的消息过期时间
*/
@Test
public void ttlMessageTest(){
MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
// 设置当前发送的消息过期时间
message.getMessageProperties().setExpiration("5000");
return message;
}
};
for (int i = 0; i < 10; i++) {
if (i == 5){
rabbitTemplate.convertAndSend(RabbitMQConfig.TTL_EXCHANGE,"qos.test","Test RabbitMQ TTL success!",messagePostProcessor);
}else {
rabbitTemplate.convertAndSend(RabbitMQConfig.TTL_EXCHANGE,"qos.test","Test RabbitMQ TTL success!");
}
}
}
}