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. maven依赖和传递

    compile (编译范围) compile是默认的范围:如果没有提供一个范围,那该依赖的范围就是编译范围.编译范围依赖在所有的classpath 中可用,同时它们也会被打包. 只有compile 才 ...

  2. python摸爬滚打之day026----网络通信流程

    1.了解概念 C\S架构: 客户端(client)和服务端(server)之间的通信. B\S架构: 浏览器(browser)和服务端之间的通信. 为什么只用一个浏览器就可以访问很多网站?  这是因为 ...

  3. 关于12C中optimizer_adaptive_features参数介绍

    optimizer_adaptive_features参数在OLAP数据仓库环境中可以获得较好的效果,实际在重上传轻查询的OLTP系统上,可以关闭这项新功能. 其主要功能是为了在语句执行过程中实时收集 ...

  4. vue 之iview

    iView-admin2.0:https://admin.iviewui.com/ 组件:https://www.iviewui.com/docs/guide/install

  5. Go 初体验 - 令人惊叹的语法 - defer.3 - defer 函数参数计算时机

    defer 函数的参数计算时机 定义一个 defer 函数,接收参数 n: 调用: 输出: 有点惊讶,为什么不是 100 200 200? go 语言里,defer 函数的参数是在定义位置被计算的,也 ...

  6. 第三章 document对象及数组

    1.数组的使用(1)声明数组var 数组名=new Array();(2)数组赋值数组名[下标]=值: 2.数组声明,分配空间,赋值同时进行var 数组名=new Array(值1,值2....)va ...

  7. fiddler学习总结--Web端抓包

    步骤一: Fiddler的基本配置:Tools-->option-->Connections: 就可以进行抓包了 步骤二: 可以通过一些设置过滤: 步骤三: 抓取HTTPS的请求:1.安装 ...

  8. puppeteer(一)环境搭建——新Web自动化工具(同selenium)

    一.简介 https://github.com/GoogleChrome/puppeteer Puppeteer是一个Node库,它提供了一个高级API来控制DevTools协议上的 Chrome或C ...

  9. git之概念图

    1.git四大区. . 2. 3. 4.

  10. Windbg程序调试系列1-Mex扩展使用总结

    最近一直在频繁使用Windbg做线上Dump调试,与微软做Case交流的时候,发现微软CSS团队,用了一个非常效率的Windbg 插件,Mex: 使用介绍: https://blogs.msdn.mi ...