rabbitmq五種模式詳解(含實現(xiàn)代碼)
一、五種模式詳解
1.簡單模式(Queue模式)
當生產(chǎn)端發(fā)送消息到交換機,交換機根據(jù)消息屬性發(fā)送到隊列,消費者監(jiān)聽綁定隊列實現(xiàn)消息的接收和消費邏輯編寫.簡單模式下,強調(diào)的一個隊列queue只被一個消費者監(jiān)聽消費.
1.1 結構

生產(chǎn)者:生成消息,發(fā)送到交換機交換機:根據(jù)消息屬性,將消息發(fā)送給隊列消費者:監(jiān)聽這個隊列,發(fā)現(xiàn)消息后,獲取消息執(zhí)行消費邏輯
1.2應用場景
常見的應用場景就是一發(fā),一接的結構
例如:
手機短信郵件單發(fā)
2.爭搶模式(Work模式)
強調(diào)的也是后端隊列與消費者綁定的結構
2.1結構

生產(chǎn)者:發(fā)送消息到交換機交換機:根據(jù)消息屬性將消息發(fā)送給隊列消費者:多個消費者,同時綁定監(jiān)聽一個隊列,之間形成了爭搶消息的效果
2.2應用場景
- 搶紅包
- 資源分配系統(tǒng)
3.路由模式(Route模式 Direct定向)
從路由模式開始,關心的就是消息如何到達的隊列,路由模式需要使用的交換機類型就是路由交換機(direct)
3.1 結構

- 生產(chǎn)端:發(fā)送消息,在消息中處理消息內(nèi)容,攜帶一個routingkey
- 交換機:接收消息,根據(jù)消息的routingkey去計算匹配后端隊列的routingkey
- 隊列:存儲交換機發(fā)送的消息
- 消費端:簡單模式 工作爭搶
3.2應用場景
- 短信
- 聊天工具
- 郵箱。。
手機號/郵箱地址,都可以是路由key
4.發(fā)布訂閱模式(Pulish/Subscribe模式 Fanout廣播)
不計算路由的一種特殊交換機
4.1結構

4.2應用場景
- 消息推送
- 廣告
5.主題模式(Topics模式 Tpoic通配符)
路由key值是一種多級路徑。中國.四川.成都.武侯區(qū)
5.1結構

生產(chǎn)端:攜帶路由key,發(fā)送消息到交換機
隊列:綁定交換機和路由不一樣,不是一個具體的路由key,而可以使用*和#代替一個范圍
| * | 字符串,只能表示一級 |
| --- | --- |
| # | 多級字符串 |
交換機:根據(jù)匹配規(guī)則,將路由key對應發(fā)送到隊列
消息路由key:
- 北京市.朝陽區(qū).酒仙橋
- 北京市.#: 匹配true
- 上海市.浦東區(qū).*: 沒匹配false
- 新疆.烏魯木齊.#
5.2 應用場景
做物流分揀的多級傳遞.
6.完整結構

二、代碼實現(xiàn)
1.創(chuàng)建SpringBoot工程
1.1 工程基本信息

1.2 依賴信息

1.3 配置文件applicasion.properties
# 應用名稱 spring.application.name=springboot-demo # Actuator Web 訪問端口 management.server.port=8801 management.endpoints.jmx.exposure.include=* management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always # 應用服務 WEB 訪問端口 server.port=8801 ######################### RabbitMQ配置 ######################## # RabbitMQ主機 spring.rabbitmq.host=127.0.0.1 # RabbitMQ虛擬主機 spring.rabbitmq.virtual-host=demo # RabbitMQ服務端口 spring.rabbitmq.port=5672 # RabbitMQ服務用戶名 spring.rabbitmq.username=admin # RabbitMQ服務密碼 spring.rabbitmq.password=admin # RabbitMQ服務發(fā)布確認屬性配置 ## NONE值是禁用發(fā)布確認模式,是默認值 ## CORRELATED值是發(fā)布消息成功到交換器后會觸發(fā)回調(diào)方法 ## SIMPLE值經(jīng)測試有兩種效果,其一效果和CORRELATED值一樣會觸發(fā)回調(diào)方法,其二在發(fā)布消息成功后使用rabbitTemplate調(diào)用waitForConfirms或waitForConfirmsOrDie方法等待broker節(jié)點返回發(fā)送結果,根據(jù)返回結果來判定下一步的邏輯,要注意的點是waitForConfirmsOrDie方法如果返回false則會關閉channel,則接下來無法發(fā)送消息到broker; spring.rabbitmq.publisher-confirm-type=simple # RabbitMQ服務開啟消息發(fā)送確認 spring.rabbitmq.publisher-returns=true ######################### simple模式配置 ######################## # RabbitMQ服務 消息接收確認模式 ## NONE:不確認 ## AUTO:自動確認 ## MANUAL:手動確認 spring.rabbitmq.listener.simple.acknowledge-mode=manual # 指定最小的消費者數(shù)量 spring.rabbitmq.listener.simple.concurrency=1 # 指定最大的消費者數(shù)量 spring.rabbitmq.listener.simple.max-concurrency=1 # 開啟支持重試 spring.rabbitmq.listener.simple.retry.enabled=true
2.簡單模式
2.1 創(chuàng)建SimpleQueueConfig 簡單隊列配置類
package com.gmtgo.demo.simple;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author 大帥
*/
@Configuration
public class SimpleQueueConfig {
/**
* 定義簡單隊列名.
*/
private final String simpleQueue = "queue_simple";
@Bean
public Queue simpleQueue() {
return new Queue(simpleQueue);
}
}
2.2 編寫生產(chǎn)者
package com.gmtgo.demo.simple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author 大帥
*/
@Slf4j
@Component
public class SimpleProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage() {
for (int i = 0; i < 5; i++) {
String message = "簡單消息" + i;
log.info("我是生產(chǎn)信息:{}", message);
rabbitTemplate.convertAndSend( "queue_simple", message);
}
}
}
2.3 編寫消費者
package com.gmtgo.demo.simple;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class SimpleConsumers {
@RabbitListener(queues = "queue_simple")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息:{}", new String(message.getBody()));
}
}
2.4 編寫訪問類
package com.gmtgo.demo.simple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 大帥
*/
@RestController
@RequestMapping(value = "/rabbitMq")
public class SimpleRabbitMqController {
@Autowired
private SimpleProducer simpleProducer;
@RequestMapping(value = "/simpleQueueTest")
public String simpleQueueTest() {
simpleProducer.sendMessage();
return "success";
}
}
2.5 測試啟動項目訪問 simpleQueueTest
訪問地址:http://127.0.0.1:8801/rabbitMq/simpleQueueTest
結果:

3.Work隊列
3.1 編寫工作配置
package com.gmtgo.demo.work;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author 大帥
*/
@Configuration
public class WorkQueueConfig {
/**
* 隊列名.
*/
private final String work = "work_queue";
@Bean
public Queue workQueue() {
return new Queue(work);
}
}
3.2 編寫生產(chǎn)者
package com.gmtgo.demo.work;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author 大帥
*/
@Slf4j
@Component
public class WorkProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage() {
for (int i = 0; i < 10; i++) {
String message = "工作消息" + i;
log.info("我是生產(chǎn)信息:{}", message);
rabbitTemplate.convertAndSend("work_queue", message);
}
}
}
3.3 編寫消費者1
package com.gmtgo.demo.work;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class WorkConsumers1 {
@RabbitListener(queues = "work_queue")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息1:{}", new String(message.getBody()));
}
}
3.4 編寫消費者2
package com.gmtgo.demo.work;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class WorkConsumers2 {
@RabbitListener(queues = "work_queue")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息2:{}", new String(message.getBody()));
}
}
3.5 編寫測試方法
package com.gmtgo.demo.work;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 大帥
*/
@RestController
@RequestMapping(value = "rabbitMq")
public class WorkRabbitMqController {
@Autowired
private WorkProducer workProducer;
@RequestMapping(value = "workQueueTest")
public String workQueueTest() {
workProducer.sendMessage();
return "success";
}
}
3.6 測試啟動項目訪問 workQueueTest
訪問地址http://127.0.0.1:8801/rabbitMq/workQueueTest
結果:

控制臺打印,發(fā)現(xiàn)10條消息 偶數(shù)條消費者1獲取,奇數(shù)條消費者2獲取,并且平均分配。
當然通過代碼實現(xiàn)按需分配,即誰的性能強,誰優(yōu)先原則,實現(xiàn)負載均衡。
配置可控分配數(shù)

4. 發(fā)布訂閱模式(Publish/Subscibe模式)
訂閱模式–多個消費者監(jiān)聽不同的隊列,但隊列都綁定同一個交換機
4.1 編寫訂閱配置類
package com.gmtgo.demo.fanout;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author 大帥
*/
@Configuration
public class FanoutQueueConfig {
/**
* 聲明隊列名.
*/
private final String fanout1 = "fanout_queue_1";
private final String fanout2 = "fanout_queue_2";
/**
* 聲明交換機的名字.
*/
private final String fanoutExchange = "fanoutExchange";
/**
* 聲明隊列.
*
* @return
*/
@Bean
public Queue fanoutQueue1() {
return new Queue(fanout1);
}
@Bean
public Queue fanoutQueue2() {
return new Queue(fanout2);
}
/**
* 聲明交換機.
*/
@Bean
public FanoutExchange exchange() {
return new FanoutExchange(fanoutExchange);
}
/**
* 隊列綁定交換機,也可在可視化工具中進行綁定.
*
* @return
*/
@Bean
public Binding bindingFanoutQueue1(Queue fanoutQueue1, FanoutExchange exchange) {
return BindingBuilder.bind(fanoutQueue1).to(exchange);
}
@Bean
public Binding bindingFanoutQueue2(Queue fanoutQueue2, FanoutExchange exchange) {
return BindingBuilder.bind(fanoutQueue2).to(exchange);
}
}
4.2 編寫訂閱生產(chǎn)者
package com.gmtgo.demo.fanout;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author 大帥
*/
@Slf4j
@Component
public class FanoutProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage() {
for (int i = 0; i < 5; i++) {
String message = "訂閱模式消息" + i;
log.info("我是生產(chǎn)信息:{}", message);
rabbitTemplate.convertAndSend("fanoutExchange", "", message);
}
}
}
4.3 編寫訂閱消費者1
package com.gmtgo.demo.fanout;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class FanoutConsumers1 {
@RabbitListener(queues = "fanout_queue_1")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息1:{}", new String(message.getBody()));
}
}
4.4 編寫訂閱消費者2
package com.gmtgo.demo.fanout;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class FanoutConsumers2 {
@RabbitListener(queues = "fanout_queue_2")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息2:{}", new String(message.getBody()));
}
}
4.5 編寫測試方法
package com.gmtgo.demo.fanout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 大帥
*/
@RestController
@RequestMapping(value = "rabbitMq")
public class FanoutRabbitMqController {
@Autowired
private FanoutProducer fanoutProducer;
@RequestMapping(value = "fanoutQueueTest")
public String fanoutQueueTest() {
fanoutProducer.sendMessage();
return "success";
}
}
3.6 測試啟動項目訪問 fanoutQueueTest

控制臺打印 ,發(fā)現(xiàn)兩個綁定了不同隊列的消費者都接受到了同一條消息查看RabbitMq 服務器:



5. 路由模式(Route模式 Direct定向)
5.1 編寫路由配置類
package com.gmtgo.demo.direct;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author 大帥
*/
@Configuration
public class DirectQueueConfig {
/**
* 聲明隊列名.
*/
private final String direct1 = "direct_queue_1";
private final String direct2 = "direct_queue_2";
/**
* 聲明交換機的名字.
*/
private final String directExchange = "directExchange";
/**
* 聲明隊列.
*
* @return
*/
@Bean
public Queue directQueue1() {
return new Queue(direct1);
}
@Bean
public Queue directQueue2() {
return new Queue(direct2);
}
/**
* 聲明路由交換機.
*
* @return
*/
@Bean
public DirectExchange directExchange() {
return new DirectExchange(directExchange);
}
/**
* 隊列綁定交換機,指定routingKey,也可在可視化工具中進行綁定.
*
* @return
*/
@Bean
Binding bindingDirectExchange1(Queue directQueue1, DirectExchange exchange) {
return BindingBuilder.bind(directQueue1).to(exchange).with("update");
}
/**
* 隊列綁定交換機,指定routingKey,也可在可視化工具中進行綁定.
*
* @return
*/
@Bean
Binding bindingDirectExchange2(Queue directQueue2, DirectExchange exchange) {
return BindingBuilder.bind(directQueue2).to(exchange).with("add");
}
}
5.2 編寫生產(chǎn)者
package com.gmtgo.demo.direct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author 大帥
*/
@Slf4j
@Component
public class DirectProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessageA() {
for (int i = 0; i < 5; i++) {
String message = "路由模式--routingKey=update消息" + i;
log.info("我是生產(chǎn)信息:{}", message);
rabbitTemplate.convertAndSend("directExchange", "update", message);
}
}
public void sendMessageB() {
for (int i = 0; i < 5; i++) {
String message = "路由模式--routingKey=add消息" + i;
log.info("我是生產(chǎn)信息:{}", message);
rabbitTemplate.convertAndSend("directExchange", "add", message);
}
}
}
5.3 編寫消費者1
package com.gmtgo.demo.direct;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class DirectConsumers1 {
@RabbitListener(queues = "direct_queue_1")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息1:{}", new String(message.getBody()));
}
}
5.4 編寫消費者2
package com.gmtgo.demo.direct;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class DirectConsumers2 {
@RabbitListener(queues = "direct_queue_2")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息2:{}", new String(message.getBody()));
}
}
5.5 編寫訪問類
package com.gmtgo.demo.direct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 大帥
*/
@RestController
@RequestMapping(value = "rabbitMq")
public class DirectRabbitMqController {
@Autowired
private DirectProducer directProducer;
@RequestMapping(value = "directQueueTest1")
public String directQueueTest1() {
directProducer.sendMessageA();
return "success";
}
@RequestMapping(value = "directQueueTest2")
public String directQueueTest2() {
directProducer.sendMessageB();
return "success";
}
}
5.6 測試啟動項目訪問directQueueTest1 , directQueueTest2
訪問地址http://127.0.0.1:8801/rabbitMq/directQueueTest1
訪問地址http://127.0.0.1:8801/rabbitMq/directQueueTest2
結果:directQueueTest1:

directQueueTest2:

6. 主題模式(Topics模式 Tpoic通配符)
6.1 編寫路由配置類
package com.gmtgo.demo.topic;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author 大帥
*/
@Configuration
public class TopicQueueConfig {
/**
* 聲明隊列名.
*/
private final String topic1 = "topic_queue_1";
private final String topic2 = "topic_queue_2";
/**
* 聲明交換機的名字.
*/
private final String topicExchange = "topicExchange";
/**
* 聲明隊列.
*
* @return
*/
@Bean
public Queue topicQueue1() {
return new Queue(topic1);
}
@Bean
public Queue topicQueue2() {
return new Queue(topic2);
}
/**
* 聲明路由交換機.
*
* @return
*/
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(topicExchange);
}
/**
* 隊列綁定交換機,指定routingKey,也可在可視化工具中進行綁定.
*
* @return
*/
@Bean
Binding bindingTopicExchange1(Queue topicQueue1, TopicExchange exchange) {
return BindingBuilder.bind(topicQueue1).to(exchange).with("topic.keyA");
}
/**
* 隊列綁定交換機,指定routingKey,也可在可視化工具中進行綁定.
* 綁定的routing key 也可以使用通配符:
* *:匹配不多不少一個詞
* #:匹配一個或多個詞
*
* @return
*/
@Bean
Binding bindingTopicExchange2(Queue topicQueue2, TopicExchange exchange) {
return BindingBuilder.bind(topicQueue2).to(exchange).with("topic.#");
}
}
6.2 編寫生產(chǎn)者
package com.gmtgo.demo.topic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author 大帥
*/
@Slf4j
@Component
public class TopicProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessageA() {
for (int i = 0; i < 5; i++) {
String message = "通配符模式--routingKey=topic.keyA消息" + i;
log.info("我是生產(chǎn)信息:{}", message);
rabbitTemplate.convertAndSend("topicExchange", "topic.keyA", message);
}
}
public void sendMessageB() {
for (int i = 0; i < 5; i++) {
String message = "通配符模式--routingKey=topic.#消息" + i;
log.info("我是生產(chǎn)信息:{}", message);
rabbitTemplate.convertAndSend("topicExchange", "topic.keyD.keyE", message);
}
}
}
6.3 編寫消費者1
package com.gmtgo.demo.topic;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class TopicConsumers1 {
@RabbitListener(queues = "topic_queue_1")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息1:{}",new String(message.getBody()));
}
}
6.4 編寫消費者2
package com.gmtgo.demo.topic;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 大帥
*/
@Slf4j
@Component
public class TopicConsumers2 {
@RabbitListener(queues = "topic_queue_2")
public void readMessage(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
log.info("我是消費信息2:{}",new String(message.getBody()));
}
}
6.5 編寫訪問類
package com.gmtgo.demo.topic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 大帥
*/
@RestController
@RequestMapping(value = "rabbitMq")
public class TopicRabbitMqController {
@Autowired
private TopicProducer topicProducer;
@RequestMapping(value = "topicQueueTest1")
public String topicQueueTest1() {
topicProducer.sendMessageA();
return "success";
}
@RequestMapping(value = "topicQueueTest2")
public String topicQueueTest2() {
topicProducer.sendMessageB();
return "success";
}
}
6.6 測試啟動項目訪問topicQueueTest1 , topicQueueTest2
- 訪問地址http://127.0.0.1:8801/rabbitMq/topicQueueTest1
- 訪問地址http://127.0.0.1:8801/rabbitMq/topicQueueTest2
- 結果:
topicQueueTest1,兩個消費者都能消費

topicQueueTest2,只有消費者2 可以消費

至此,五種隊列的實現(xiàn)已結束!
7. 實現(xiàn)生產(chǎn)者消息確認
7.1 配置文件
######################### RabbitMQ配置 ######################## # RabbitMQ主機 spring.rabbitmq.host=127.0.0.1 # RabbitMQ虛擬主機 spring.rabbitmq.virtual-host=demo # RabbitMQ服務端口 spring.rabbitmq.port=5672 # RabbitMQ服務用戶名 spring.rabbitmq.username=admin # RabbitMQ服務密碼 spring.rabbitmq.password=admin # RabbitMQ服務發(fā)布確認屬性配置 ## NONE值是禁用發(fā)布確認模式,是默認值 ## CORRELATED值是發(fā)布消息成功到交換器后會觸發(fā)回調(diào)方法 ## SIMPLE值經(jīng)測試有兩種效果,其一效果和CORRELATED值一樣會觸發(fā)回調(diào)方法,其二在發(fā)布消息成功后使用rabbitTemplate調(diào)用waitForConfirms或waitForConfirmsOrDie方法等待broker節(jié)點返回發(fā)送結果,根據(jù)返回結果來判定下一步的邏輯,要注意的點是waitForConfirmsOrDie方法如果返回false則會關閉channel,則接下來無法發(fā)送消息到broker; spring.rabbitmq.publisher-confirm-type=simple # 連接超時時間 spring.rabbitmq.connection-timeout=20000 # RabbitMQ服務開啟消息發(fā)送確認 spring.rabbitmq.publisher-returns=true ######################### simple模式配置 ######################## # RabbitMQ服務 消息接收確認模式 ## NONE:不確認 ## AUTO:自動確認 ## MANUAL:手動確認 spring.rabbitmq.listener.simple.acknowledge-mode=manual # 指定最小的消費者數(shù)量 spring.rabbitmq.listener.simple.concurrency=1 # 指定最大的消費者數(shù)量 spring.rabbitmq.listener.simple.max-concurrency=1 # 每次只消費一個消息 spring.rabbitmq.listener.simple.prefetch=1 # 開啟支持重試 spring.rabbitmq.listener.simple.retry.enabled=true # 啟用強制信息,默認為false spring.rabbitmq.template.mandatory=true
7.2 編寫消息發(fā)送確認類 RabbitConfirmCallback
package com.gmtgo.demo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
/**
* @author 大帥
*/
@Slf4j
public class RabbitConfirmCallback implements RabbitTemplate.ConfirmCallback {
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
log.info("=======ConfirmCallback=========");
log.info("correlationData {} " , correlationData);
log.info("ack = {}" , ack);
log.info("cause = {}" , cause);
log.info("=======ConfirmCallback=========");
}
}
7.3 編寫消息發(fā)送交換機返回機制RabbitConfirmReturnCallBack
package com.gmtgo.demo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
/**
* @author 大帥
*/
@Slf4j
public class RabbitConfirmReturnCallBack implements RabbitTemplate.ReturnCallback {
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
log.info("--------------ReturnCallback----------------");
log.info("message = " + message);
log.info("replyCode = {}", replyCode);
log.info("replyText = {}", replyText);
log.info("exchange = {}", exchange);
log.info("routingKey = {}", routingKey);
log.info("--------------ReturnCallback----------------");
}
}
7.4 RabbitMQ配置
在我們的rabbit隊列配置類里設置RabbitTemplate
舉例:
package com.gmtgo.demo.topic;
import com.gmtgo.demo.config.RabbitConfirmCallback;
import com.gmtgo.demo.config.RabbitConfirmReturnCallBack;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* @author 大帥
*/
@Configuration
public class TopicQueueConfig {
@Autowired
private RabbitTemplate rabbitTemplate;
@PostConstruct
public void initRabbitTemplate() {
// 設置生產(chǎn)者消息確認
rabbitTemplate.setConfirmCallback(new RabbitConfirmCallback());
rabbitTemplate.setReturnCallback(new RabbitConfirmReturnCallBack());
}
/**
* 聲明隊列名.
*/
private final String topic1 = "topic_queue_1";
private final String topic2 = "topic_queue_2";
/**
* 聲明交換機的名字.
*/
private final String topicExchange = "topicExchange";
/**
* 聲明隊列.
*
* @return
*/
@Bean
public Queue topicQueue1() {
return new Queue(topic1);
}
@Bean
public Queue topicQueue2() {
return new Queue(topic2);
}
/**
* 聲明路由交換機.
*
* @return
*/
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(topicExchange);
}
/**
* 隊列綁定交換機,指定routingKey,也可在可視化工具中進行綁定.
*
* @return
*/
@Bean
Binding bindingTopicExchange1(Queue topicQueue1, TopicExchange exchange) {
return BindingBuilder.bind(topicQueue1).to(exchange).with("topic.keyA");
}
/**
* 隊列綁定交換機,指定routingKey,也可在可視化工具中進行綁定.
* 綁定的routing key 也可以使用通配符:
* *:匹配不多不少一個詞
* #:匹配一個或多個詞
*
* @return
*/
@Bean
Binding bindingTopicExchange2(Queue topicQueue2, TopicExchange exchange) {
return BindingBuilder.bind(topicQueue2).to(exchange).with("topic.#");
}
}
啟動項目發(fā)送消息,消息被正常消費,confim回調(diào)返回ack=true如果我們將exchange修改,發(fā)送到一個不存在的exchange中,會怎么樣呢?
會發(fā)現(xiàn)confirm回調(diào)為false,打印出結果為不存在topicExchange1111的交換機

如果我們在消費端處理邏輯時出錯會怎么樣呢?修改消費端代碼我們在消費時讓它報錯

confirm回調(diào)為true,但是在rabbitmq的web界面會發(fā)現(xiàn)存在5條沒有消費的消息

如果我們把
channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
中最后一個參數(shù)改為false呢,會發(fā)現(xiàn)在web管理界面沒有未被消費的消息,說明這條消息已經(jīng)被摒棄。
實際開發(fā)中,到底是打回到隊列呢還是摒棄,要看自己的需求,但是打回隊列應該有次數(shù)限制,不然會陷入死循環(huán)。
繼續(xù)測試,將routingKey修改為一個沒有的key,
7.5 結論
- 如果消息沒有到exchange,則confirm回調(diào),ack=false
- 如果消息到達exchange,則confirm回調(diào),ack=true
- exchange到queue成功,則不回調(diào)return
- exchange到queue失敗,則回調(diào)return
8. 項目示例代碼:
下載地址:springboot-rabbitmq-demo_1619322789961
到此這篇關于rabbitmq五種模式詳解(含實現(xiàn)代碼)的文章就介紹到這了,更多相關rabbitmq五種模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringCloud通過Feign傳遞List類型參數(shù)方式
這篇文章主要介紹了SpringCloud通過Feign傳遞List類型參數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
springboot中如何配置LocalDateTime JSON返回時間戳
這篇文章主要介紹了springboot中如何配置LocalDateTime JSON返回時間戳問題。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
JavaWeb基于Session實現(xiàn)的用戶登陸注銷方法示例
為了安全起見,session常常用來保存用戶的登錄信息。那么服務器是怎么來實現(xiàn)的呢?下面這篇文章就來給大家介紹了關于JavaWeb基于Session實現(xiàn)的用戶登陸注銷的相關資料,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧。2017-12-12
java實現(xiàn)一個接口調(diào)取另一個接口(接口一調(diào)取接口二)
這篇文章主要介紹了java實現(xiàn)一個接口調(diào)取另一個接口(接口一調(diào)取接口二),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09

