傳奇網(wǎng)站傳奇寧波優(yōu)化seo是什么
Lison
<dreamlison@163.com>
, v1.0.0
, 2023.06.22
七種模式介紹與代碼演示
文章目錄
- 七種模式介紹與代碼演示
- 四大交換機
- 四種交換機介紹
- 工作模式
- 簡單模式(Hello World)
- 工作隊列模式(Work queues)
- 訂閱模式(Publish/Subscribe)
- 路由模式(Routing)
- 主題模式(Topics)
- 遠(yuǎn)程過程調(diào)用(RPC)
- 發(fā)布者確認(rèn)(Publisher Confirms)
- 代碼演示
- 簡單模式
- 工作隊列模式
- 發(fā)布訂閱模式
- 路由模式
- 主題模式
- SpringBoot整合RabbitMQ
- 引入依賴基礎(chǔ)配置
- 生產(chǎn)者
- 消費者
四大交換機
交換機概念
- 交換機可以理解成具有路由表的路由程序,僅此而已。每個消息都有一個稱為路由鍵(routing key)的屬性,就是一個簡單的字符串。
- 最新版本的RabbitMQ有四種交換機類型,分別是Direct exchange、Fanout exchange、Topic exchange、Headers exchange。
- 交換機的作用: 生產(chǎn)者向broker(rabbitmq服務(wù)器)發(fā)送消息,交換機通過生產(chǎn)者綁定的路由鍵,將消息推送到不同的消息隊列中。而消費者,只綁定隊列,從隊列中獲取消息。
- 以上三種類型的發(fā)送精準(zhǔn)順序為:點對點類型 > 通配符類型 > 廣播類型
四種交換機介紹
- 直連交換機(Direct exchange): 具有路由功能的交換機,綁定到此交換機的時候需要指定一個routing_key,交換機發(fā)送消息的時候需要routing_key,會將消息發(fā)送道對應(yīng)的隊列
- 扇形交換機(Fanout exchange): 廣播消息到所有隊列,沒有任何處理,速度最快
- 主題交換機(Topic exchange): 在直連交換機基礎(chǔ)上增加模式匹配,也就是對routing_key進行模式匹配,
*
代表一個單詞,#
代表多個單詞 - 首部交換機(Headers exchange): 忽略routing_key,使用Headers信息(一個Hash的數(shù)據(jù)結(jié)構(gòu))進行匹配,優(yōu)勢在于可以有更多更靈活的匹配規(guī)則
交換機參數(shù)
- name: 交換機名稱
- type: 交換機類型 direct,topic,fanout,headers
- durability: 是否需要持久化,true 為持久化
- auto delete: 當(dāng)最后一個綁定到 Exchange 上的隊列被刪除后,Exchange 就沒有綁定的隊列了,自動刪除該 Exchange
- internal: 當(dāng)前 Exchange 是否為內(nèi)部交換機,默認(rèn)為 false,客戶端無法直接發(fā)送消息到這個交換機中,只能通過交換機路由到交換機這種方式
- arguments: 擴展參數(shù),用于擴展 AMQP 協(xié)議自制定化使用
工作模式
簡單模式(Hello World)
做最簡單的事情,一個生產(chǎn)者對應(yīng)一個消費者,RabbitMQ相當(dāng)于一個消息代理,負(fù)責(zé)將A的消息轉(zhuǎn)發(fā)給B
應(yīng)用場景: 將發(fā)送的電子郵件放到消息隊列,然后郵件服務(wù)在隊列中獲取郵件并發(fā)送給收件人
工作隊列模式(Work queues)
在多個消費者之間分配任務(wù)(競爭的消費者模式),一個生產(chǎn)者對應(yīng)多個消費者,一般適用于執(zhí)行資源密集型任務(wù),單個消費者處理不過來,需要多個消費者進行處理
應(yīng)用場景: 一個訂單的處理需要10s,有多個訂單可以同時放到消息隊列,然后讓多個消費者同時處理,這樣就是并行了,而不是單個消費者的串行情況
訂閱模式(Publish/Subscribe)
一次向許多消費者發(fā)送消息,一個生產(chǎn)者發(fā)送的消息會被多個消費者獲取,也就是將消息將廣播到所有的消費者中。
應(yīng)用場景: 更新商品庫存后需要通知多個緩存和多個數(shù)據(jù)庫,這里的結(jié)構(gòu)應(yīng)該是:
- 一個fanout類型交換機扇出兩個個消息隊列,分別為緩存消息隊列、數(shù)據(jù)庫消息隊列
- 一個緩存消息隊列對應(yīng)著多個緩存消費者
- 一個數(shù)據(jù)庫消息隊列對應(yīng)著多個數(shù)據(jù)庫消費者
路由模式(Routing)
有選擇地(Routing key)接收消息,發(fā)送消息到交換機并且要指定路由key ,消費者將隊列綁定到交換機時需要指定路由key,僅消費指定路由key的消息
應(yīng)用場景: 如在商品庫存中增加了1臺iphone12,iphone12促銷活動消費者指定routing key為iphone12,只有此促銷活動會接收到消息,其它促銷活動不關(guān)心也不會消費此routing key的消息
主題模式(Topics)
根據(jù)主題(Topics)來接收消息,將路由key和某模式進行匹配,此時隊列需要綁定在一個模式上,#
匹配一個詞或多個詞,*
只匹配一個詞。
應(yīng)用場景: 同上,iphone促銷活動可以接收主題為iphone的消息,如iphone12、iphone13等
遠(yuǎn)程過程調(diào)用(RPC)
如果我們需要在遠(yuǎn)程計算機上運行功能并等待結(jié)果就可以使用RPC,具體流程可以看圖。應(yīng)用場景:需要等待接口返回數(shù)據(jù),如訂單支付
發(fā)布者確認(rèn)(Publisher Confirms)
與發(fā)布者進行可靠的發(fā)布確認(rèn),發(fā)布者確認(rèn)是RabbitMQ擴展,可以實現(xiàn)可靠的發(fā)布。在通道上啟用發(fā)布者確認(rèn)后,RabbitMQ將異步確認(rèn)發(fā)送者發(fā)布的消息,這意味著它們已在服務(wù)器端處理。
應(yīng)用場景: 對于消息可靠性要求較高,比如錢包扣款
代碼演示
代碼中沒有對后面兩種模式演示,有興趣可以自己研究
簡單模式
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class SimpleQueueSender {private final static String QUEUE_NAME = "simple_queue";public static void main(String[] args) throws IOException, TimeoutException {ConnectionFactory factory = new ConnectionFactory();factory.setHost("127.0.0.1");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();// 聲明隊列// queue:隊列名// durable:是否持久化// exclusive:是否排外 即只允許該channel訪問該隊列 一般等于true的話用于一個隊列只能有一個消費者來消費的場景// autoDelete:是否自動刪除 消費完刪除// arguments:其他屬性channel.queueDeclare(QUEUE_NAME, false, false, false, null);//消息內(nèi)容String message = "simplest mode message";channel.basicPublish("", QUEUE_NAME, null, message.getBytes());System.out.println("[x]Sent '" + message + "'");//最后關(guān)閉通關(guān)和連接channel.close();connection.close();}
}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class SimpleQueueReceiver {private final static String QUEUE_NAME = "simple_queue";public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {// 獲取連接ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.queueDeclare(QUEUE_NAME, false, false, false, null);DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received '" +delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");};channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});System.out.println("----");}
}
工作隊列模式
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class QueueWorkReceiver1 {private final static String QUEUE_NAME = "queue_work";public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {// 獲取連接ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.queueDeclare(QUEUE_NAME, false, false, false, null);// 同一時刻服務(wù)器只會發(fā)送一條消息給消費者channel.basicQos(1);DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received '" +delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");};channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});}
}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class QueueWorkReceiver2 {private final static String QUEUE_NAME = "queue_work";public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {// 獲取連接ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.queueDeclare(QUEUE_NAME, false, false, false, null);// 同一時刻服務(wù)器只會發(fā)送一條消息給消費者channel.basicQos(1);DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received '" +delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");};channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});}
}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class QueueWorkSender {private final static String QUEUE_NAME = "queue_work";public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();// 聲明隊列channel.queueDeclare(QUEUE_NAME, false, false, false, null);for (int i = 0; i < 100; i++) {String message = "work mode message" + i;channel.basicPublish("", QUEUE_NAME, null, message.getBytes());System.out.println("[x] Sent '" + message + "'");Thread.sleep(i * 10);}channel.close();connection.close();}
}
發(fā)布訂閱模式
package com.lison.upgrade.middleware.rabbitmq;import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;public class PublishSubscribeReceive1 {private static final String EXCHANGE_NAME = "logs";public static void main(String[] argv) throws Exception {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.exchangeDeclare(EXCHANGE_NAME, "fanout");String queueName = channel.queueDeclare().getQueue();channel.queueBind(queueName, EXCHANGE_NAME, "");System.out.println(" [*] Waiting for messages. To exit press CTRL+C");// 訂閱消息的回調(diào)函數(shù)DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received '" + message + "'");};// 消費者,有消息時出發(fā)訂閱回調(diào)函數(shù)channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});}
}
package com.lison.upgrade.middleware.rabbitmq;import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;public class PublishSubscribeReceive2 {private static final String EXCHANGE_NAME = "logs";public static void main(String[] argv) throws Exception {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.exchangeDeclare(EXCHANGE_NAME, "fanout");String queueName = channel.queueDeclare().getQueue();channel.queueBind(queueName, EXCHANGE_NAME, "");System.out.println(" [*] Waiting for messages. To exit press CTRL+C");// 訂閱消息的回調(diào)函數(shù)DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received2 '" + message + "'");};// 消費者,有消息時出發(fā)訂閱回調(diào)函數(shù)channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});}
}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;public class PublishSubscribeSender {private static final String EXCHANGE_NAME = "logs";public static void main(String[] argv) throws Exception {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.exchangeDeclare(EXCHANGE_NAME, "fanout");String message = "publish subscribe message";channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));System.out.println(" [x] Sent '" + message + "'");channel.close();connection.close();}
}
路由模式
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class QueueRoutingReceiver1 {private final static String QUEUE_NAME = "queue_routing";private final static String EXCHANGE_NAME = "exchange_direct";public static void main(String[] args) throws IOException, TimeoutException {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.queueDeclare(QUEUE_NAME, false, false, false, null);// 指定路由的key,接收key和key2channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key");channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key2");channel.basicQos(1);DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received '" +delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");};channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});}}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class QueueRoutingReceiver2 {private final static String QUEUE_NAME = "queue_routing2";private final static String EXCHANGE_NAME = "exchange_direct";public static void main(String[] args) throws IOException, TimeoutException {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.queueDeclare(QUEUE_NAME, false, false, false, null);// 僅接收key2channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key2");channel.basicQos(1);DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received '" +delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");};channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});}
}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class QueueRoutingSender {private final static String EXCHANGE_NAME = "exchange_direct";private final static String EXCHANGE_TYPE = "direct";public static void main(String[] args) throws IOException, TimeoutException {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);factory.setUsername("admin");factory.setPassword("123456");Connection connection = factory.newConnection();Channel channel = connection.createChannel();// 交換機聲明channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);// 只有routingKey相同的才會消費String message = "routing mode message";channel.basicPublish(EXCHANGE_NAME, "key2", null, message.getBytes());System.out.println("[x] Sent '" + message + "'");
// channel.basicPublish(EXCHANGE_NAME, "key", null, message.getBytes());
// System.out.println("[x] Sent '" + message + "'");channel.close();connection.close();}
}
主題模式
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class Receiver1 {private final static String QUEUE_NAME = "queue_topic";private final static String EXCHANGE_NAME = "exchange_topic";public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.queueDeclare(QUEUE_NAME, false, false, false, null);// 可以接收key.1channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key.*");channel.basicQos(1);DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received '" +delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");};channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});}
}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class Receiver2 {private final static String QUEUE_NAME = "queue_topic2";private final static String EXCHANGE_NAME = "exchange_topic";private final static String EXCHANGE_TYPE = "topic";public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.queueDeclare(QUEUE_NAME, false, false, false, null);// *號代表單個單詞,可以接收key.1channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "*.*");// #號代表多個單詞,可以接收key.1.2channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "*.#");channel.basicQos(1);DeliverCallback deliverCallback = (consumerTag, delivery) -> {String message = new String(delivery.getBody(), "UTF-8");System.out.println(" [x] Received '" +delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");};channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});}
}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;import java.io.IOException;
import java.util.concurrent.TimeoutException;public class Sender {private final static String EXCHANGE_NAME = "exchange_topic";private final static String EXCHANGE_TYPE = "topic";public static void main(String[] args) throws IOException, TimeoutException {ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setPort(5672);Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);String message = "topics model message with key.1";channel.basicPublish(EXCHANGE_NAME, "key.1", null, message.getBytes());System.out.println("[x] Sent '" + message + "'");String message2 = "topics model message with key.1.2";channel.basicPublish(EXCHANGE_NAME, "key.1.2", null, message2.getBytes());System.out.println("[x] Sent '" + message2 + "'");channel.close();connection.close();}
}
SpringBoot整合RabbitMQ
引入依賴基礎(chǔ)配置
1、創(chuàng)建SpringBoot項目,引入RabbitMQ起步依賴
<!-- RabbitMQ起步依賴 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2、寫配置文件
spring:rabbitmq:host: 127.0.0.1port: 5672username: adminpassword: 123456virtual-host: /
#日志格式
logging:pattern:console: '%d{HH:mm:ss.SSS} %clr(%-5level) --- [%-15thread] %cyan(%-50logger{50}):%msg%n'
SpringBoot整合RabbitMQ時,需要在配置類創(chuàng)建隊列和交換機,寫法如下:
@Configuration
public class RabbitConfig {private final String EXCHANGE_NAME = "boot_topic_exchange";private final String QUEUE_NAME = "boot_queue";// 創(chuàng)建交換機@Bean("bootExchange")public Exchange getExchange() {return ExchangeBuilder.topicExchange(EXCHANGE_NAME) // 交換機類型.durable(true) // 是否持久化.build();}// 創(chuàng)建隊列@Bean("bootQueue")public Queue getMessageQueue() {return new Queue(QUEUE_NAME); // 隊列名}// 交換機綁定隊列@Beanpublic Binding bindMessageQueue(@Qualifier("bootExchange") Exchange exchange, @Qualifier("bootQueue") Queue queue) {return BindingBuilder.bind(queue).to(exchange).with("#.message.#").noargs();}
}
生產(chǎn)者
SpringBoot整合RabbitMQ時,提供了工具類RabbitTemplate發(fā)送消息,編寫生產(chǎn)者時只需要注入RabbitTemplate即可發(fā)送消息。
@SpringBootTest
public class TestProducer {// 注入RabbitTemplate工具類@Autowiredprivate RabbitTemplate rabbitTemplate;@Testpublic void testSendMessage(){/*** 發(fā)送消息* 參數(shù)1:交換機* 參數(shù)2:路由key* 參數(shù)3:要發(fā)送的消息*/rabbitTemplate.convertAndSend("boot_topic_exchange","message","這個是生產(chǎn)者發(fā)送消息!");}
}
消費者
@Component
public class Consumer {// 監(jiān)聽隊列@RabbitListener(queues = "boot_queue")public void listen_message(String message){System.out.println("發(fā)送短信:"+message);}
}
啟動項目,可以看到消費者會消費隊列中的消息