Spring Boot集成和使用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。首先,它定义了一个配置类RabbitMQConfig
,在该类中,它创建了一个名为queueName
的持久队列,一个名为topicExchange
的交换器,并将队列绑定到交换器上,使用了一个路由键routingKey
。然后,它配置了一个SimpleMessageListenerContainer
来监听队列上的消息,并将其绑定到一个名为\`RabbitMQListe
评论已关闭