在SpringBoot中使用RabbitMQ,需要引入相關的依賴并配置RabbitMQ的連接信息。以下是具體的步驟:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
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);
}
}
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);
}
}
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進行消息的發送和接收操作。當發送一條消息時,消息生產者會將消息發送到指定的交換機和路由鍵,消息消費者會監聽指定的隊列并接收消息。