springboot mq demo
时间: 2023-09-02 20:15:44 浏览: 54
下面是一个使用 Spring Boot 和 RabbitMQ 的示例代码:
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. 创建一个消息接收者
```java
@Component
public class Receiver {
@RabbitListener(queues = "myQueue")
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
}
```
4. 创建一个消息发送者
```java
@Component
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMessage(String message) {
amqpTemplate.convertAndSend("myQueue", message);
System.out.println("Sent message: " + message);
}
}
```
5. 在启动类中添加以下代码以测试
```java
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private Sender sender;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
sender.sendMessage("Hello World!");
}
}
```
这样,当启动应用程序时,它将发送一条消息到名为“myQueue”的队列中,然后 Receiver 将接收并打印该消息。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)