在SpringBoot中使用RabbitMQ,需要引入相关的依赖并配置RabbitMQ的连接信息。以下是具体的步骤:
引入RabbitMQ的依赖:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId></dependency>在application.properties文件中配置RabbitMQ的连接信息:spring.rabbitmq.host=localhostspring.rabbitmq.port=5672spring.rabbitmq.username=guestspring.rabbitmq.password=guest创建一个RabbitMQ的消息生产者:import org.springframework.amqp.core.AmqpTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class RabbitMQProducer { @Autowired private AmqpTemplate rabbitTemplate; public void send(String message) { rabbitTemplate.convertAndSend("exchange", "routingKey", message); }}创建一个RabbitMQ的消息消费者:import org.springframework.amqp.rabbit.annotation.RabbitListener;import org.springframework.stereotype.Component;@Componentpublic class RabbitMQConsumer { @RabbitListener(queues = "queue") public void receiveMessage(String message) { System.out.println("Received message: " + message); }}在启动类中添加@EnableRabbit注解启用RabbitMQ支持:import org.springframework.amqp.rabbit.annotation.EnableRabbit;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@EnableRabbitpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}通过以上步骤,就可以在SpringBoot中使用RabbitMQ进行消息的发送和接收操作。当发送一条消息时,消息生产者会将消息发送到指定的交换机和路由键,消息消费者会监听指定的队列并接收消息。




