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。首先,它定义了一个配置类,在该类中创建了一个队列、一个交换器和一个绑定。然后,它配置了一个消息监听器容器,该容器使用MessageListenerAdapter来调用一个消息处理方法。最后,提供了一个消息处理类,其中包含处理消息的方法。这个例子简单明了,并且清晰地展示了整个集成过程。
评论已关闭