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. 可视化&地图__公司收集

    原文地址:https://github.com/zhongcaiwei/Data-visualization-technology-sharing 一.数据可视化企业(部分) 数字冰雹 光启元-腾讯 ...

  2. python基础(17)-IO模型&selector模块

    先说一下IO发生时涉及的对象和步骤.对于一个network IO (这里我们以read举例),它会涉及到两个系统对象,一个是调用这个IO的process (or thread),另一个就是系统内核(k ...

  3. React之ant design的table表格序号连续自增

    render(text,record,index){     return(       <span>{(pagination.current-1)*10+index+1}</spa ...

  4. make pycaffe时候报错:Makefile:501: recipe for target 'python/caffe/_caffe.so' failed

    安装caffe-ssd编译环境的时候报错: python/caffe/_caffe.cpp:10:31: fatal error: numpy/arrayobject.h: No such file ...

  5. manjaro使用国内软件源

    虽然manjaro是基于arch修改的,但毕竟还是有些改动,如果可以用manjaro仓库里的,尽量不要用arch的源.如果嫌官方的软件源慢,可以直接一条命令修改成国内的软件源 sudo pacman- ...

  6. 2017.11.18 手把手教你学51单片机-点亮LED

    In Doing We Learning 在操作中学习.如果只是光看教程,没有实际的操作,对编程语言的理解很空泛,所以决定从单片机中学习C语言. #include<reg52.h>     ...

  7. qt creator中编辑Makefile的设置

    在qt creator中编辑Makefile时的Tab键总是不能识别,需要这样设置

  8. MySQL插入命令_INSERT INTO

    MySQL允许将一个或多个元组插入已存在的table中. 格式:INSERT INTO  表名 (属性名1,属性名2,属性名3) VALUES (value1,value2,value3);     ...

  9. SQL Server 2012安装时报错,错误 0x80070422怎么解决?解决方法。

    步骤一: Win+R打开运行窗口,输入services.msc 打开服务窗口 步骤二: 找到并启用"Windows Update" 成功进入下一步!

  10. 6、Spring-Kafka4

    4.1. Using Spring for Apache Kafka This section offers detailed explanations of the various concerns ...