概述
当我们遇到业务场景,在规定时间内要处理完某业务,就可以用到TTL(time to live生存时间)。
RabbitMQ 允许为消息和队列设置 TTL。消息 TTL 可以应用于单个队列、一组队列或逐个消息应用。
配置
照例,定义交换机、队列,绑定关系。队列设置参数"x-message-ttl"=5000(ms);
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @Description TODO
* @Author chanyu
* @Date 2022/5/27 16:57
* @Version 1.0
**/
@Configuration
public class TtlRabbitConfiguration {
@Bean
public DirectExchange ttlExchange(){
return new DirectExchange("ttl.order.exchange",true,false);
}
@Bean
public Queue ttlDirectQueue(){
Map<String, Object> map = new HashMap<>();
// 队列设置存活时间,单位ms,必须是整形数据。
map.put("x-message-ttl",5000);
Queue queue = new Queue("ttl.direct.queue",true,false,false,map);
return queue;
}
@Bean
public Binding ttlDirectBinding(){
return BindingBuilder.bind(ttlDirectQueue()).to(ttlExchange()).with("ttl");
}
}
生产者
发消息其实与direct方式一样。
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
/**
* @Description TODO
* @Author chanyu
* @Date 2022/5/27 16:52
* @Version 1.0
**/
@Slf4j
@Service
public class OrderService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void orderTtl(String userId , String goodsId , int num , String unit){
// 订单写入
String orderId = UUID.randomUUID().toString();
String msg = "创建订单"+orderId+",用户"+userId+"购买"+num+unit+"商品"+"goodsId";
log.info("创建订单{},用户{}购买{}{}商品{}",orderId,userId,num,unit,goodsId);
// 扣减库存
String exchangeName = "ttl.order.exchange";
String routingKey = "ttl";
// 发布消息
rabbitTemplate.convertAndSend(exchangeName,routingKey,msg);
}
}
验证
import com.cy.rabbitmqproducer.service.OrderService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class RabbitmqProducerApplicationTests {
@Autowired
private OrderService orderService;
@Test
void orderTtl() throws InterruptedException {
orderService.orderTtl("1","1",3,"件");
}
}
执行orderTtl(),ttl.direct.queue 队列将加入1条消息,并在5s后消失。