idea spring boot框架搭建MQ
时间: 2023-12-01 14:04:00 浏览: 94
spring下实现MQ
4星 · 用户满意度95%
以下是使用Spring Boot框架搭建MQ的步骤:
1.首先,在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2.在application.properties文件中添加以下配置:
```properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
```
3.创建一个消息生产者类,用于发送消息到MQ:
```java
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MessageProducer {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMessage(String message) {
amqpTemplate.convertAndSend("queueName", message);
}
}
```
4.创建一个消息消费者类,用于从MQ接收消息:
```java
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class MessageConsumer {
@RabbitListener(queues = "queueName")
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
}
```
5.在启动类中添加@EnableRabbit注解,启用RabbitMQ:
```java
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);
}
}
```
以上就是使用Spring Boot框架搭建MQ的步骤。
阅读全文