springboot integrates rabbitmq to implement message sending and consumption
springboot integrates rabbitmq to implement message sending and consumption
Spring Boot provides automated configuration of RabbitMQ , making it very easy to integrate RabbitMQ.
First, you need to introduce amqp-client and spring-boot-starter-amqp dependencies in the pom.xml file :
<dependency>
<groupId>com.[rabbitmq](/search?q=rabbitmq)</groupId>
<artifactId>amqp-client</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
Next, you need to configure the RabbitMQ connection information in the application.properties file:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
Then write the message sender:
@Component
public class RabbitMQSender {
private final RabbitTemplate rabbitTemplate;
public RabbitMQSender(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void send(String message) {
rabbitTemplate.convertAndSend("my-exchange", "my-routing-key", message);
}
}
Among them, my-exchange and my-routing-key are switch and routing keys that need to be defined by yourself.
Finally write the message consumer:
@Component
public class RabbitMQReceiver {
@RabbitListener(queues = "my-queue")
public void receive(String message) {
System.out.println("Received message: " + message);
}
}
Among them, my-queue is also a queue that needs to be defined by yourself.
After the above steps are completed, the sending and consumption of messages can be realized.