一.Topic-Exchange 模式:
模糊匹配,比較Message的routing key和Queue的binding key,按規則匹配成功時,Message纔會發送到該Queue。
匹配規則:
- 第一種: * 匹配單個字母或數字
- 第二種: # 匹配0~多個字母或數字
項目使用上一篇中的項目 rabbitmq-produce、rabbitmq-consumer
二.rabbitmq-produce的改動
2.1 在rabbitmq-produce中,新增一個TopicRabbitConfig配置類
TopicRabbitConfig的代碼如下:
package com.example.rabbitmqproduce.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Topic-exchange 配置類
* 模糊匹配,比較Message的routing key和Queue的binding key,按規則匹配成功時,Message纔會發送到該Queue
* 匹配規則:
* 第一種: * 匹配單個字母或數字
* 第二種: # 匹配0~多個字母或數字
*/
@Configuration
public class TopicRabbitConfig {
private Logger logger = LoggerFactory.getLogger(TopicRabbitConfig.class);
//定義 Topic-exchange模型 的隊列名
private static final String topicQueueNameA = "topicQueueNameA";
//定義 Topic-exchange模型 的隊列名
private static final String topicQueueNameB = "topicQueueNameB";
//定義 Topic-exchange模型 的交換機名
private static final String topicExchangeName = "topicExchange";
//定義 Topic-exchange模型 的bingingKey
//他只會接收包含topicQueue.msg的消息
private static final String topicBindingKeyA = "topicQueue.msg";
//定義 Topic-exchange模型 的bingingKey
//他只會接收topicQueue開頭的消息
private static final String topicBindingKeyB = "topicQueue.#";
/**
* 隊列 起名
*/
@Bean
public Queue topiocA() {
return new Queue(topicQueueNameA);
}
@Bean
public Queue topicB() {
return new Queue(topicQueueNameB);
}
/**
* Topic交換機 起名:topicExchange
*/
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(topicExchangeName);
}
/**
* 綁定 將隊列和交換機綁定
* @return
*/
@Bean
public Binding bindingTopicA() {
return BindingBuilder.bind(topiocA()).to(topicExchange()).with(topicBindingKeyA);
}
/**
* 綁定 將隊列和交換機綁定
* @return
*/
@Bean
public Binding bindingTopicB() {
return BindingBuilder.bind(topicB()).to(topicExchange()).with(topicBindingKeyB);
}
}
2.2 新建一個Topic-exchange模式 的消息生產者TopicExchangeProduce類
TopicExchangeProduce 類 的代碼如下:
package com.example.rabbitmqproduce.produce;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Topic-exchange模式 的消息生產者
* @Component 注入到Spring容器中
*/
@Component
public class TopicExchangeProduce {
//注入一個AmqpTemplate來發布消息
@Autowired
private AmqpTemplate rabbitTemplate;
private Logger logger = LoggerFactory.getLogger(TopicExchangeProduce.class);
//topic 交換機名稱
private static final String topicExchangeName = "topicExchange";
//topic 的RoutingKey
private static final String topicRouteKeyA = "topicQueue.msg";
//topic 的RoutingKey
private static final String topicRouteKeyB = "topicQueue.jax.master";
/**
* topicA 發送消息
*/
public void sendMessageTopicA() {
String messageId = String.valueOf(UUID.randomUUID());
String messageData = "hello!亞索 面對疾風吧";
String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Map<String,Object> map=new HashMap<>();
map.put("messageId",messageId);
map.put("messageData",messageData);
map.put("createTime",createTime);
logger.info("發送的內容 : " + map.toString());
//將消息攜帶綁定鍵值:topicQueue.msg 發送到交換機topicExchange
rabbitTemplate.convertAndSend(topicExchangeName, topicRouteKeyA, map);
}
/**
* topicB 發送消息
*/
public void sendMessageTopicB() {
String messageId = String.valueOf(UUID.randomUUID());
String messageData = "hello!賈克斯 我可以打10個";
String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Map<String,Object> map=new HashMap<>();
map.put("messageId",messageId);
map.put("messageData",messageData);
map.put("createTime",createTime);
logger.info("發送的內容 : " + map.toString());
//將消息攜帶綁定鍵值:topicQueue.jax.master 發送到交換機topicExchange
rabbitTemplate.convertAndSend(topicExchangeName, topicRouteKeyB, map);
}
}
2.3 寫個測試的TestController類
代碼如下:
package com.example.rabbitmqproduce.controller;
import com.example.rabbitmqproduce.produce.DirectExchangeProduce;
import com.example.rabbitmqproduce.produce.FanoutExchangeProduce;
import com.example.rabbitmqproduce.produce.RabbitMqProduce;
import com.example.rabbitmqproduce.produce.TopicExchangeProduce;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("TestController")
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
private RabbitMqProduce rabbitMqProduce;
@Autowired
private DirectExchangeProduce directExchangeProduce;
@Autowired
private FanoutExchangeProduce fanoutExchangeProduce;
@Autowired
private TopicExchangeProduce topicExchangeProduce;
/**
* 測試基本消息模型(簡單隊列)
*/
@RequestMapping(value = "/testSimpleQueue", method = RequestMethod.POST)
public void testSimpleQueue() {
logger.info("測試基本消息模型(簡單隊列)SimpleQueue---開始");
for (int i = 0; i < 10; i++) {
rabbitMqProduce.sendMessage();
}
logger.info("測試基本消息模型(簡單隊列)SimpleQueue---結束");
}
/**
* 測試 Direct-exchange模式
*/
@RequestMapping(value = "/directExchangeTest", method = RequestMethod.POST)
public void directExchangeTest() {
logger.info("測試 Direct-exchange模式 隊列名爲directQueue---開始");
for (int i = 0; i < 10; i++) {
directExchangeProduce.sendMessage();
}
logger.info("測試 Direct-exchange模式 隊列名爲directQueue---結束");
}
/**
* 測試 Fanout-exchange模式
*/
@RequestMapping(value = "/fanoutExchangeTest", method = RequestMethod.POST)
public void fanoutExchangeTest() {
logger.info("測試 fanout-exchange模式 隊列名爲fanoutQueue---開始");
fanoutExchangeProduce.sendMessage();
logger.info("測試 fanout-exchange模式 隊列名爲fanoutQueue---結束");
}
/**
* 測試 Topic-exchange模式 topicA 和 topicB
*/
@RequestMapping(value = "/topictExchangeTest", method = RequestMethod.POST)
public void topictExchangeTest() {
logger.info("測試 topict-exchange模式 隊列名爲topictQueueNameA---開始");
topicExchangeProduce.sendMessageTopicA();
logger.info("測試 topict-exchange模式 隊列名爲topictQueueNameA---結束");
logger.info("測試 topict-exchange模式 隊列名爲topictQueueNameB---開始");
topicExchangeProduce.sendMessageTopicB();
logger.info("測試 topict-exchange模式 隊列名爲topictQueueNameB---結束");
}
}
三.rabbitmq-consumer的改動
3.1 新建一個Topic-exchange模式 的消息消費者TopicExchangeConsumerA類 和 TopicExchangeConsumerB類
TopicExchangeConsumerA代碼如下:
package com.example.rabbitmqconsumer.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* Topic-exchange模式 的消息消費者
* @RabbitListener(queues = "topicQueueNameA") 監聽名爲topicQueueNameA的隊列
*/
@Component
@RabbitListener(queues = "topicQueueNameA")
public class TopicExchangeConsumerA {
@Autowired
private AmqpTemplate rabbitmqTemplate;
private Logger logger = LoggerFactory.getLogger(TopicExchangeConsumerA.class);
/**
* 消費消息
* @RabbitHandler 代表此方法爲接受到消息後的處理方法
*/
@RabbitHandler
public void receiveMessage(Map msg){
logger.info("TopicExchangeA消費者接收到的消息 :" + msg.toString());
}
}
TopicExchangeConsumerB代碼如下:
package com.example.rabbitmqconsumer.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* Topic-exchange模式 的消息消費者
* @RabbitListener(queues = "topicQueueNameB") 監聽名爲topicQueueNameB的隊列
*/
@Component
@RabbitListener(queues = "topicQueueNameB")
public class TopicExchangeConsumerB {
@Autowired
private AmqpTemplate rabbitmqTemplate;
private Logger logger = LoggerFactory.getLogger(TopicExchangeConsumerB.class);
/**
* 消費消息
* @RabbitHandler 代表此方法爲接受到消息後的處理方法
*/
@RabbitHandler
public void receiveMessage(Map msg){
logger.info("TopicExchangeB消費者接收到的消息 :" + msg.toString());
}
}
四.測試
首先啓動生產者rabbitmq-produce項目。在postman或瀏覽器上訪問:
http://localhost:8783/TestController/topictExchangeTest POST請求
這時可以在rabbitmq-produce的控制檯可以看到
然後再啓動消費者rabbitmq-consumer工程,在rabbitmq-consumer可以看到: