SpringBoot中整合RabbitMQ(测试+部署上线 最完整)
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
private static final String TOPIC_EXCHANGE = "topicExchange";
private static final String QUEUE_NAME = "queueName";
@Bean
Queue queue() {
return new Queue(QUEUE_NAME, true);
}
@Bean
TopicExchange exchange() {
return new TopicExchange(TOPIC_EXCHANGE);
}
@Bean
Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("routingKey");
}
@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(QUEUE_NAME);
container.setMessageListener(listenerAdapter);
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(RabbitMQListener receiver) {
return new MessageListenerAdapter(receiver, "handleMessage");
}
}
public class RabbitMQListener {
public void handleMessage(String message) {
// 处理接收到的消息
}
}
这个代码示例展示了如何在Spring Boot应用程序中配置和连接RabbitMQ,创建交换器、队列并将它们绑定在一起。同时,它还配置了一个监听器容器来监听指定队列的消息,并将接收到的消息委托给一个处理器(RabbitMQListener)进行处理。这个例子涵盖了RabbitMQ在Spring Boot中的基本使用,并且是在生产环境中部署RabbitMQ的一个很好的实践。
评论已关闭