【RabbitMQ实战】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。首先,我们定义了一个配置类RabbitMQConfig
,在这个类中,我们创建了一个名为queueName
的队列,一个名为topicExchange
的交换器,并将队列绑定到交换器上,路由键为routingKey
。然后,我们创建了一个SimpleMessageListenerContainer
,它会监听队列上的消息,并使用MessageListenerAdapter
来适配一个消息接收者RabbitMQListener
。在RabbitMQListener
类中,我们定义了一个方法handleMessage
来处理接收到的消息。
评论已关闭