RabbitMQ+死信队列 做延迟消费
<!--rabbitmq的配置-->
#rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
<!-- RabbitMQ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
<!--配置队列与交换机->
/**
* 订单延迟的处理
*/
@Configuration
public class OrderQueryConfig {
/**
* @return 定义一个队列用于订单的接受
*/
@Bean
public Queue productQueue() {
return new Queue("PQ");
}
/**
* 定义一个死信队列
* @return
*/
@Bean
public Queue orderQueue(){
return QueueBuilder.durable("OQ").withArgument("x-dead-letter-exchange","PE")
.withArgument("x-dead-letter-routing-key", "product").build();
}
/**
* @return 返回一个订单直连交换机
*/
@Bean
public DirectExchange productExchange(){
return new DirectExchange("PE");
}
/**
* @return 返回一个直连交换机
*/
@Bean
public DirectExchange orderExchange(){
return new DirectExchange("OE");
}
/**
* 把交换机与接受订单队列绑定
* @return
*/
@Bean
public Binding productBind(){
return BindingBuilder.bind(productQueue()).to(productExchange()).with("product");
}
@Bean
public Binding orderBind1(){
return BindingBuilder.bind(orderQueue()).to(orderExchange()).with("order");
}
<!--向管道中发送消息-->
@Autowired
private AmqpTemplate amqpTemplate;
public Integer pastDispose(Integer commid, final String pasttime){
amqpTemplate.convertAndSend("OE", "order", commid, new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
// 设置过期时间
message.getMessageProperties().setExpiration(pasttime);
return message;
}
});
return commid;
}
<!--监听消费-->
@RabbitListener(queues = "PQ")
public void addorderlistnenr(Integer commid){
xxxxxxxx
}