SpringBoot中怎么使用RabbitMQ

2024-04-18,

SpringBoot中使用RabbitMQ,需要引入相关的依赖并配置RabbitMQ的连接信息。以下是具体的步骤:

  1. 引入RabbitMQ的依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. 在application.properties文件中配置RabbitMQ的连接信息:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
  1. 创建一个RabbitMQ的消息生产者:
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQProducer {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send(String message) {
        rabbitTemplate.convertAndSend("exchange", "routingKey", message);
    }
}
  1. 创建一个RabbitMQ的消息消费者:
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQConsumer {

    @RabbitListener(queues = "queue")
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}
  1. 在启动类中添加@EnableRabbit注解启用RabbitMQ支持:
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableRabbit
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

通过以上步骤,就可以在SpringBoot中使用RabbitMQ进行消息的发送和接收操作。当发送一条消息时,消息生产者会将消息发送到指定的交换机和路由键,消息消费者会监听指定的队列并接收消息。

《SpringBoot中怎么使用RabbitMQ.doc》

下载本文的Word格式文档,以方便收藏与打印。