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. 20175320 2018-2019-2 《Java程序设计》第5周学习总结

    20175320 2018-2019-2 <Java程序设计>第5周学习总结 教材学习内容总结 本周学习了教材的第六章的内容.在这章中介绍了接口与实现,着重讲了接口是如何定义并实现以及如何 ...

  2. TensorRT层和每个层支持的精度模式

    下表列出了TensorRT层和每个层支持的精确模式.它还列出了该层在深度学习加速器(DLA)上运行的能力.有关附加约束的更多信息,请参见 DLA Supported Layershttps://doc ...

  3. 《Redis 优化》

    一:管道技术 - 由于 redis 和 客户端是使用 TCP 连接的,那么在使用中就会产生往返耗时. - 虽然可能单条影响并不大,但是如果执行较多的命令会对性能产生影响. - 使用管道原理和 keep ...

  4. toolbar按钮添加图标

    需要toolbar关联imagelist组件,imagelist组件添加需要的图片,在toolbar新建按钮,按钮中选择相应图表.

  5. C++(+类型加强 +加入面向对象)

    1.c++中所有变量可以在使用前定义. ; i< ; i++) { ; j< ; j++) { do_sth; } } 2. c++ 中可以获得 register 变量的地址. regis ...

  6. python框架之Django(4)-视图&路由

    视图 负责接收请求和返回响应 FBV和CBV FBV FBV(function base views) 就是在视图里使用函数处理请求. from django.conf.urls import url ...

  7. vs添加github代码库

    1.安装git for windows 2.在vs中工具->扩展和更新,安装github extension 3.在项目中右键,添加源码到git,之后配置git,然后选择同步或者commit即可

  8. 【LeetCode每天一题】Jump Game II(跳跃游戏II)

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  9. HDU 2586 How far away(LCA+邻接表)

    How far away &题解: 和上篇是一样的题,这用的是lca方法做的, 不知道为什么,把数组开到80000 就a了 >_< 哈 我现在知道为什么了,因为我的rmq数组没有乘 ...

  10. word之常用功能

    0.word区域:标题栏.快速访问工具栏.功能区.功能按钮.导航窗口.编辑区.水平垂直滑动条.状态栏 1.更改office主题.文件---帐户---office主题.(传统白色.浅灰色.深灰色) 2. ...