【SpringBoot】SpringBoot整合RabbitMQ消息中间件,实现延迟队列和死信队列
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
public static final String DELAY_EXCHANGE_NAME = "delay_exchange";
public static final String DEAD_LETTER_QUEUE_NAME = "dead_letter_queue";
public static final String QUEUE_NAME = "sample_queue";
public static final String ROUTING_KEY = "sample_routing_key";
@Bean
Queue deadLetterQueue() {
return QueueBuilder.durable(DEAD_LETTER_QUEUE_NAME)
.deadLetterExchange(DELAY_EXCHANGE_NAME)
.deadLetterRoutingKey(ROUTING_KEY)
.build();
}
@Bean
DirectExchange delayExchange() {
return new DirectExchange(DELAY_EXCHANGE_NAME);
}
@Bean
Queue sampleQueue() {
return QueueBuilder.durable(QUEUE_NAME)
.build();
}
@Bean
Binding bindingDelayExchange(Queue sampleQueue, DirectExchange delayExchange) {
return BindingBuilder.bind(sampleQueue)
.to(delayExchange)
.with(ROUTING_KEY);
}
@Bean
Binding bindingDeadLetterQueue(Queue deadLetterQueue, DirectExchange delayExchange) {
return BindingBuilder.bind(deadLetterQueue)
.to(delayExchange)
.with(ROUTING_KEY);
}
}
这个配置类定义了一个延迟消息队列(通过delay_exchange
实现)和一个死信队列(当消息在延迟队列中等待超过指定时间后,会被重新发送到dead_letter_queue
)。这里使用了Spring AMQP的QueueBuilder
和BindingBuilder
来简化配置。这个配置类可以作为Spring Boot应用的一部分,通过@Configuration
注解被Spring容器自动加载。
评论已关闭