目錄
- 一、概述
- 二、基礎配置
- 三、生產者
- 四、消費者
一、概述
這是一篇Java集成RabbitMQ的入門案例,在這里我們做一個小案例,來體會一下RabbitMQ的魅力。
首先我們要做的就是創建一個生產者一個消費者:
- 生產者直接向RabbitMQ的隊列(Queue)
simple.queue
中發送消息。 - 消費者負責接收隊列(Queue)
simple.queue
發送過來的消息。
生產者源碼
消費者源碼
二、基礎配置
當我們的生產者要發送和接收消息時,首先需要再RabbitMQ中創建一個通道。
三、生產者
- 加載POM文件
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>
</dependencies>
- 配置YML文件
server:port: 8021
spring:#給項目來個名字application:name: rabbitmq-provider#配置rabbitMq 服務器rabbitmq:host: 127.0.0.1port: 5672username: adminpassword: adminvirtualHost: /mamfconnection-timeout: 5000requested-heartbeat: 30
- 在Test中編寫測試代碼
package com.ming;import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class SpringAmqpTest {@Autowiredprivate RabbitTemplate rabbitTemplate;@Testpublic void testSend() {for (int i = 0; i < 10; i++) {String queueName = "simple.queue"; // 隊列名稱String messahe = String.format("hello %s, spring amqp!", i + 1); // 消息rabbitTemplate.convertAndSend(queueName, messahe); // 發送}}
}
四、消費者
消費者的前兩部分與生產者是一樣的,消費者需要創建一個監聽,用于監聽simple.queue
隊列。
package com.ming.listens;import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class RabbitmqListen {@RabbitListener(queues = "simple.queue")public void listenSimpleQueue(String message){System.out.println(String.format("消費者收到了simple.queue: %s", message));}
}
當從生產者發送消息時,消費者就會監聽到數據。