RabbitMQ(4) TopicExchange
topic 是RabbitMQ中最灵活的一种方式,可以根据routing_key自由的绑定不同的队列
生产者工程
package com.example.demo.rabbitMq.exchange.topic; 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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class TopicRabbitConfig { public static final String TOPIC_MESSAGE = "topic.message";
public static final String TOPIC_MESSAGE_S = "topic.messages";
public static final String USER_MESSAGE = "user.message"; /**
* 武器库
*/
public static final String ARM_QUEUE = "arm.queue"; @Bean
public Queue queueTopicMessage() {
return new Queue(TopicRabbitConfig.TOPIC_MESSAGE);
} @Bean
public Queue queueTopicMessages() {
return new Queue(TopicRabbitConfig.TOPIC_MESSAGE_S);
} @Bean
public Queue queueUserMessage() {
return new Queue(TopicRabbitConfig.USER_MESSAGE);
} @Bean
public Queue queueArm() {
return new Queue(TopicRabbitConfig.ARM_QUEUE);
} @Bean
TopicExchange exchange() {
return new TopicExchange("topicExchange");
} @Bean
Binding bindingExchangeMessage(Queue queueTopicMessage, TopicExchange exchange) {
//所有匹配routingKey=topic.message的消息,将放入Queue[name="topic.message"]
return BindingBuilder.bind(queueTopicMessage).to(exchange).with("topic.message");
} @Bean
Binding bindingExchangeMessages(Queue queueTopicMessages, TopicExchange exchange) {
//所有匹配routingKey=topic.# 的消息,将放入Queue[name="topic.messages"]
return BindingBuilder.bind(queueTopicMessages).to(exchange).with("topic.#");
} @Bean
Binding bindingExchangeUserMessage(Queue queueUserMessage, TopicExchange exchange) {
///所有匹配routingKey=user.# 的消息,将放入Queue[name="user.messages"]
return BindingBuilder.bind(queueUserMessage).to(exchange).with("user.#");
} @Bean
Binding bindingExchangeArm(Queue queueArm, TopicExchange exchange) {
return BindingBuilder.bind(queueArm).to(exchange).with("arm.#");
}
}
发送消息
package com.example.demo.rabbitMq.exchange.topic; import com.example.demo.dto.User;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component
public class TopicSender {
@Autowired
private AmqpTemplate rabbitTemplate; public void send1() {
User user = new User();
user.setUserName("Sender1.....");
user.setMobile("1111111111");
rabbitTemplate.convertAndSend("topicExchange","topic.message",user);
} public void send2() {
User user = new User();
user.setUserName("Sender2.....");
user.setMobile("2222222");
rabbitTemplate.convertAndSend("topicExchange","topic.messages",user);
} public void send3() {
User user = new User();
user.setUserName("Sender3.....");
user.setMobile("33333");
rabbitTemplate.convertAndSend("topicExchange","user.message",user);
}
}
消费者工程
package com.example.demo.rabbitMq.exchange.topic; 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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class TopicRabbitConstant {
public static final String TOPIC_MESSAGE = "topic.message";
public static final String TOPIC_MESSAGE_S = "topic.messages";
public static final String USER_MESSAGE = "user.message";
}
package com.example.demo.rabbitMq.exchange.topic; import com.example.demo.dto.User;
import com.example.demo.utils.Base64Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
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.io.IOException; @Component
@RabbitListener(queues = TopicRabbitConstant.TOPIC_MESSAGE)
public class TopicReceiver1 { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private AmqpTemplate rabbitTemplate; @RabbitHandler
public void process(User user) {
System.out.println("Receiver1 : " + user);
} public void rev1(){
//手动去获取消息
logger.info("获取Queue[topic.message]消息>>>");
Message mesg = rabbitTemplate.receive("topic.message");
System.out.println(mesg);
if(null != mesg){
byte[] body = mesg.getBody();
try {
User u = (User) Base64Utils.byteToObj(body);
//获取字符串数据
System.out.println(u);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
测试:
启动消费者工程,生产者,执行如下方法
@Test
public void send1() throws Exception {
//会匹配到topic.#和topic.message 两个Receiver都可以收到消息
for (int i = 0, size = 10; i < size; i++) {
topicSender.send1();
}
}
也可以不用监听的方式,手动自主获取队列消息,如消费工程:
例如生产者工程TopicRabbitConfig.java添加武器队列:
/**
* 武器库
*/
public static final String ARM_QUEUE = "arm.queue"; @Bean
public Queue queueArm() {
return new Queue(TopicRabbitConfig.ARM_QUEUE);
} @Bean
Binding bindingExchangeArm(Queue queueArm, TopicExchange exchange) {
return BindingBuilder.bind(queueArm).to(exchange).with("arm.#");
}
生产武器:
public void send4() {
//生产一批武器
List<String> list = new ArrayList<String>(); list.add("手枪");
list.add("步枪");
list.add("机枪"); rabbitTemplate.convertAndSend("topicExchange","arm.gun",list);
}
@Test
public void send4() throws Exception {
topicSender.send4();
}
消费者:
package com.example.demo.rabbitMq; import com.example.demo.dto.User;
import com.example.demo.rabbitMq.exchange.topic.TopicReceiver1;
import com.example.demo.utils.Base64Utils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource;
import java.io.IOException;
import java.util.List; @SpringBootTest
@RunWith(SpringRunner.class)
public class RabbitMqRevTest {
private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private AmqpTemplate rabbitTemplate; @Test
public void topicRev1(){
rev1();
} public void rev1(){
//手动去获取消息
logger.info("获取Queue[arm.gun]消息>>>");
Message mesg = rabbitTemplate.receive("arm.queue");
System.out.println(mesg);
if(null != mesg){
byte[] body = mesg.getBody();
try {
List u = (List) Base64Utils.byteToObj(body);
//获取字符串数据
System.out.println(u);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
测试:
样例代码:
https://github.com/xiaozhuanfeng?tab=repositories
RabbitMQ(4) TopicExchange的更多相关文章
- RabbitMQ的TopicExchange通配符问题
TopicExchange交换机支持使用通配符*.# *号只能向后多匹配一层路径. #号可以向后匹配多层路径.
- 使用rabbitmq实现集群im聊天服务器消息的路由
这个地址图文会更清晰:https://www.jianshu.com/p/537e87c64ac7 单机系统的时候,客户端和连接都有同一台服务器管理. image.png 在本地维护一份userI ...
- SpringBoot 企业级核心技术学习专题
专题 专题名称 专题描述 001 Spring Boot 核心技术 讲解SpringBoot一些企业级层面的核心组件 002 Spring Boot 核心技术章节源码 Spring Boot 核心技术 ...
- springboot(八):RabbitMQ详解
RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用. 消息中间件在互联网公司的使用中越来越多,刚才还看到新闻阿里将RocketMQ捐献给了apa ...
- spring amqp rabbitmq fanout配置
基于spring amqp rabbitmq fanout配置如下: 发布端 <rabbit:connection-factory id="rabbitConnectionFactor ...
- RabbitMQ学习笔记4-使用fanout交换器
fanout交换器会把发送给它的所有消息发送给绑定在它上面的队列,起到广播一样的效果. 本里使用实际业务中常见的例子, 订单系统:创建订单,然后发送一个事件消息 积分系统:发送订单的积分奖励 短信平台 ...
- RabbitMQ学习笔记3-使用topic交换器
topic的路由规则里使用[.]号分隔单词,使用[*]号匹配1个单词,使用[#]匹配多个.和多个*. 在下面的例子中: logger.*可以匹配logger.error和logger.warning, ...
- RabbitMQ - 实例操作
以前在单项目中用过RabbitMQ,没有问题 不过这次在分布式项目中使用RabbitMQ中有点搞糊涂了,但是实际上是没有问题的,思路清晰就行 简单看一下实际操作的示例吧: 资源文件中需要配置基本的ra ...
- spring boot实战(第十二篇)整合RabbitMQ
前言 最近几篇文章将围绕消息中间件RabbitMQ展开,对于RabbitMQ基本概念这里不阐述,主要讲解RabbitMQ的基本用法.Java客户端API介绍.spring Boot与RabbitMQ整 ...
随机推荐
- 把vim改装为source sight
本文在ubuntu18.04上实践. 主要为VIM 安装4个插件: taglist,srcexpl,NERD_tree,ctrlp 1,taglist.vim :https://www.vim.org ...
- [ipsec][strongswan] 用strongswan pki工具生成自签名证书
如题.我在实验环境里,分别要为两个endpoint(T9和T129)生成证书. 证书是如何生成的呢? 证书是由根证书机构签发的.申请证书的人将request提交给根证书机构,然后根证书机构根据requ ...
- iptables 分析(1)
原文:http://blog.chinaunix.net/uid-24207747-id-2622900.html iptables 是用户空间中用于管理包过滤及NAT 等的工具应用程序.它设置防火墙 ...
- Linux下的文件系统2
2017-03-13 上文针对VFS的基本信息做了介绍,并简单介绍了VFS涉及的几个数据机构,本节结合LInux源码,对各个结构之间的关系进行分析. 一.总体架构图 总体架构图如上图所示,结合进程访问 ...
- 列表 & 元组& join & range
一:列表(增删改查,列表的嵌套,列表的循环) 1)增加 append (在列表的尾部增加) insert (插入) insert(插入的位置,插入的内容) extend ...
- python练习题-day12
用列表推导式做下列小题 (1) 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母 lst1=["admhdja","aksaudj","fh&q ...
- 1、jeecg 笔记开篇
1. 前言 终究还是入了 jeecg 的 "坑",国庆后公司采用该框架开发,故开篇记录. 虽说入"坑",但不得不承认 jeecg 确实是一个非常强大的平台. 其 ...
- mongodb删除重复数据
注:mongodb当前版本是3.4.3 插入六条数据: 查询存在重复的数据: 查询并循环删除重复数据: 删除语句解析: db.userInfo.aggregate([ { ...
- django时区设置 media配置 日期截断函数 上传图片管理设计方案
1.django时区 修改一下app里的设置 TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True # 不用UTC时间 USE_TZ ...
- DAX/PowerBI系列 - 库存总价值(Inventory Value)
DAX/PowerBI系列 - 库存总价值(Inventory Value) 欢迎交流与骚扰 难度: ★★☆☆☆(2星) 适用: ★★☆☆☆(2星) 概况: 有多少货(库存)当然重要(对于运营人员), ...