赞
踩
SpringBoot整合RabbitMQ的步骤如下:
pom.xml
文件中添加RabbitMQ的依赖。<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.properties
或application.yml
文件中添加RabbitMQ的配置信息,如RabbitMQ服务器的地址、端口、用户名、密码、交换机、队列和路由键等。spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
# 配置交换机
my.rabbitmq.exchange.name=myExchange
my.rabbitmq.exchange.type=direct
# 配置队列
my.rabbitmq.queue.name=myQueue
# 配置路由键
my.rabbitmq.routing.key=myRoutingKey
@Service
public class RabbitMQProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage(String exchangeName, String routingKey, String message) {
rabbitTemplate.convertAndSend(exchangeName, routingKey, message);
}
}
@Service
public class RabbitMQConsumer {
@RabbitListener(queues = "myQueue")
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
}
在这里,@RabbitListener
注解用于标注监听队列的方法。
@Bean
注解来定义它们。@Configuration public class RabbitMQConfig { @Bean public DirectExchange exchange() { return new DirectExchange(my.rabbitmq.exchange.name); } @Bean public Queue queue() { return new Queue(my.rabbitmq.queue.name); } @Bean public Binding binding(Queue queue, DirectExchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(my.rabbitmq.routing.key); } }
注意:在实际应用中,你可能还需要考虑更多的配置,如消息持久化、消息确认机制、死信队列、消息序列化/反序列化等。具体的配置和使用方式可以参考RabbitMQ和SpringBoot的官方文档。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。