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的更多相关文章

  1. RabbitMQ的TopicExchange通配符问题

    TopicExchange交换机支持使用通配符*.# *号只能向后多匹配一层路径. #号可以向后匹配多层路径.

  2. 使用rabbitmq实现集群im聊天服务器消息的路由

    这个地址图文会更清晰:https://www.jianshu.com/p/537e87c64ac7 单机系统的时候,客户端和连接都有同一台服务器管理.   image.png 在本地维护一份userI ...

  3. SpringBoot 企业级核心技术学习专题

    专题 专题名称 专题描述 001 Spring Boot 核心技术 讲解SpringBoot一些企业级层面的核心组件 002 Spring Boot 核心技术章节源码 Spring Boot 核心技术 ...

  4. springboot(八):RabbitMQ详解

    RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用. 消息中间件在互联网公司的使用中越来越多,刚才还看到新闻阿里将RocketMQ捐献给了apa ...

  5. spring amqp rabbitmq fanout配置

    基于spring amqp rabbitmq fanout配置如下: 发布端 <rabbit:connection-factory id="rabbitConnectionFactor ...

  6. RabbitMQ学习笔记4-使用fanout交换器

    fanout交换器会把发送给它的所有消息发送给绑定在它上面的队列,起到广播一样的效果. 本里使用实际业务中常见的例子, 订单系统:创建订单,然后发送一个事件消息 积分系统:发送订单的积分奖励 短信平台 ...

  7. RabbitMQ学习笔记3-使用topic交换器

    topic的路由规则里使用[.]号分隔单词,使用[*]号匹配1个单词,使用[#]匹配多个.和多个*. 在下面的例子中: logger.*可以匹配logger.error和logger.warning, ...

  8. RabbitMQ - 实例操作

    以前在单项目中用过RabbitMQ,没有问题 不过这次在分布式项目中使用RabbitMQ中有点搞糊涂了,但是实际上是没有问题的,思路清晰就行 简单看一下实际操作的示例吧: 资源文件中需要配置基本的ra ...

  9. spring boot实战(第十二篇)整合RabbitMQ

    前言 最近几篇文章将围绕消息中间件RabbitMQ展开,对于RabbitMQ基本概念这里不阐述,主要讲解RabbitMQ的基本用法.Java客户端API介绍.spring Boot与RabbitMQ整 ...

随机推荐

  1. ASP.NET Core ResponseCaching:基于 VaryByHeader 定制缓存 Key

    ASP.NET Core ResponseCaching 提供了缓存http响应内容的能力,通过它可以在本地内存中直接缓存http响应内容,这是速度最快的服务端缓存,省却了网络传输与生成响应内容的开销 ...

  2. Golang覆盖写入文件的小坑

    记录一点Golang文件操作的笔记,环境:Ubuntu // 删除文件 func removeFile() { err := os.Remove("test.txt") if er ...

  3. 装饰者模式在JDK和Mybatis中是怎么应用的? java io包

    https://mp.weixin.qq.com/s/-bj71dBylRHRqiPorOpVyg 原创: 李立敏 Java识堂 3月10日 有一个卖煎饼的店铺找上了你,希望你能给她们的店铺开发一个收 ...

  4. Java开发想尝试大数据和数据挖掘,如何规划学习?

    大数据火了几年了,但是今年好像进入了全民大数据时代,本着对科学的钻(zhun)研(bei)精(tiao)神(cao),我在17年年初开始自学大数据,后经过系统全面学习,于这个月跳槽到现任公司. 现在已 ...

  5. I2C驱动框架 (kernel-3.4.2)

    先用韦老师的图: 注:  新版本内核的i2c驱动框架采用了    i2c_client -------> i2c_bus_type  <-------- i2c_driver   框架 如 ...

  6. 安装Linux系统,学习Linux操作基础

    20189230杨静怡 2018-2019-2 <移动平台开发实践>第1周学习总结 安装Linux系统内容总结 一.学习"基于VirtualBox虚拟机安装Ubuntu图文教程& ...

  7. Mysql数据库配置参数详解大全

    名称 是否需要重启 值 允许值 描述 auto_increment_increment 否 1 1-65,535 auto_increment_increment和auto_increment_off ...

  8. Centos下,Docker部署Yapi接口管理平台(详细得令人发指)

    接口测试的工具很多,公司引进了接口管理平台Yapi,自己尝试直接搭建,从安装Nodejs到配置MongoDB数据库,再到安装yapi的时候,遇到浏览器打开本地服务器Ip地址后,没有显示部署内容...没 ...

  9. pprint

    pprint = pretty printer 经常用来打印 字典.json 打印出的格式会是较为标准的格式 目的:方便调试,查看中间结果,因为觉得设断点调试相对麻烦. [运行环境:macOS 10. ...

  10. 'webpack-dev-server' 不是内部或外部命令,也不是可运行的程序

    npm install  webpack-dev-server --save