RabbitMQ延时队列之一

队列配置

@Configuration
public class SendDelayQueueConfig {
	
	// 声明死信交换机
	@Bean
	public Exchange dealLetterExchange() {
		return ExchangeBuilder.directExchange("senddelay-xdl-exchange").durable(true).build();
	}
	
	// 声明死信队列
	@Bean
	public Queue expirationDealLetterQueue() {
		Map arguments = new HashMap();
		arguments.put("x-dead-letter-exchange", "senddelay-xdl-exchange");
		arguments.put("x-dead-letter-routing-key", "senddelay-forward-routingkey");
		return QueueBuilder.durable("senddelay-xdl-queue").withArguments(arguments).build();
	}
	
	// 死信队列 通过 senddelay-xdl-routingkey 绑定 死信交换机
	@Bean
	public Binding dealLetterBinding() {
		return new Binding("senddelay-xdl-queue", Binding.DestinationType.QUEUE, "senddelay-xdl-exchange", "senddelay-xdl-routingkey", null);
	}
	
	// 声明转发队列
	@Bean
    public Queue expirationQueue() {
        return QueueBuilder.durable("senddelay-forward-queue").build();
    }
	
	// 转发队列 通过 senddelay-routingkey 绑定 死信交换机
	@Bean
	public Binding expirationBinding() {
		return new Binding("senddelay-forward-queue", Binding.DestinationType.QUEUE, "senddelay-xdl-exchange", "senddelay-forward-routingkey", null);
	}
}

效果如下:

RabbitMQ延时队列之一_第1张图片

发送代码

@RunWith(SpringRunner.class)
@SpringBootTest
public class SendDelayTest {

	@Autowired
	RabbitProducer rabbitProducer;
	
	@Test
	public void testAsyncSend() throws InterruptedException {
		String message = "发送时间" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		String msgId = UUID.randomUUID().toString().replace("-", "");
		
		rabbitProducer.asyncSend("senddelay-xdl-exchange", "senddelay-xdl-routingkey", "1"+message, msgId, 1);
		rabbitProducer.asyncSend("senddelay-xdl-exchange", "senddelay-xdl-routingkey", "2"+message, msgId, 2);
		rabbitProducer.asyncSend("senddelay-xdl-exchange", "senddelay-xdl-routingkey", "4"+message, msgId, 4);
		rabbitProducer.asyncSend("senddelay-xdl-exchange", "senddelay-xdl-routingkey", "8"+message, msgId, 8);
		rabbitProducer.asyncSend("senddelay-xdl-exchange", "senddelay-xdl-routingkey", "16"+message, msgId, 16);
		Thread.sleep(5000);
	}
}

消费代码

@Slf4j
@Component
public class SendDelayConsumerTest {
	
	@RabbitListener(queues = "senddelay-forward-queue")
	public void handler(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag)
			throws IOException {
		log.info(message.getMessageProperties().getConsumerQueue() + "消费信息:"+ new String(message.getBody()) + " 当前时间:" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		channel.basicAck(deliveryTag, false);
		log.info(message.getMessageProperties().getConsumerQueue() + "消费结束");
	}
}

 

你可能感兴趣的:(RabbitMQ,rabbit,mq,延时队列)