2.2 直接模式(Direct)
2.2.1 什麼是Direct模式
我們需要將消息發給唯一一個節點時使用這種模式,這是最簡單的一種形式。
任何發送到Direct Exchange的消息都會被轉發到RouteKey中指定的Queue。
1.一般情況可以使用rabbitMQ自帶的Exchange:”"(該Exchange的名字爲空字符串,下文稱其爲default Exchange)。
2.這種模式下不需要將Exchange進行任何綁定(binding)操作
3.消息傳遞時需要一個“RouteKey”,可以簡單的理解爲要發送到的隊列名字。
4.如果vhost中不存在RouteKey中指定的隊列名,則該消息會被拋棄。
2.2.2 創建隊列
做下面的例子前,我們先建立一個叫test1的隊列。
Durability:是否做持久化 Durable(持久) transient(臨時)
Auto delete : 是否自動刪除
2.2.3 代碼實現-消息生產者
(1)創建工程rabbitmq_demo,引入amqp起步依賴 ,pom.xml如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
(2)編寫配置文件application.yml
spring:
rabbitmq:
host: 192.168.184.134
(3)編寫啓動類
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
(4)編寫測試類
@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class MqTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSend(){
rabbitTemplate.convertAndSend("test1","我要紅包");
}
}
運行測試方法
2.2.4 代碼實現-消息消費者
(1)編寫消息消費者類
@Component
@RabbitListener(queues="test1" )
public class Customer1 {
@RabbitHandler
public void showMessage(String message){
System.out.println("itcast接收到消息:"+message);
}
}
(2)運行啓動類,可以在控制檯看到剛纔發送的消息
2.2.5 測試
開啓多個消費者工程,測試運行消息生產者工程,會發現只有一個消費者工程可以接收
到消息。
如何在IDEA中多次啓動同一個程序呢?
(1)選擇IDEA右上角的類名稱按鈕
(2)選擇Edit Configurations
(3)在彈出窗口中取消單例模式 ,點擊OK
server:
port: 9202
運行後在控制檯可以看到多個窗口