赞
踩
RabbitMQ之主题模式(topic)简介
主题(Topic):可理解为消息的key,用于匹配某条消息的生产者和消费者
将路由键和某种匹配模式一起使用
#表示多个
*表示1个
代码参考
生产者
- /**
- * topic 队列
- *
- * 将路由键和某种匹配模式一起使用
- *
- * #表示多个 *表示1个
- *
- * @author zhang
- *
- */
- public class TopicSend {
-
- public static final String TOPIC_NAME = "topic_test";
-
- public static void main(String[] args) throws IOException, TimeoutException {
-
- // 获取链接
- Connection connection = ConnectHelp.getConnect();
-
- // 建立通道
- Channel channel = connection.createChannel();
-
- // 建立转换机 指定类型
- channel.exchangeDeclare(TOPIC_NAME, "topic");
-
- // 数据的定义
- String msg = "send msg test &&";
-
- // 发送数据
- channel.basicPublish(TOPIC_NAME, "food.add", null, msg.getBytes());
-
- System.out.println("main :" + msg);
- // 关闭
- channel.close();
- connection.close();
-
- }
-
- }

消费者1
- /**
- * Topic 消费者1
- *
- * @author zhang
- *
- */
- public class TopicRevc1 {
- public static final String TOPIC_NAME = "topic_test";
- public static final String QUEUE_NAME = "topic_queue_1";
-
- public static void main(String[] args) throws IOException, TimeoutException {
-
- // 建立连接
- Connection connection = ConnectHelp.getConnect();
-
- // 建立通道
- final Channel channel = connection.createChannel();
-
- // 声明队列
- channel.queueDeclare(QUEUE_NAME, false, false, false, null);
-
- // 绑定队列
- channel.queueBind(QUEUE_NAME, TOPIC_NAME, "food.select");
- // 每次只接受一个数据
- channel.basicQos(1);
-
- // 获取数据
- DefaultConsumer consumer = new DefaultConsumer(channel) {
- @Override
- public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
- throws IOException {
-
- String msg = new String(body, "utf-8");
- System.out.println("TOP1:" + msg);
- // 可以接受下一个消息
- channel.basicAck(envelope.getDeliveryTag(), false);
- }
- };
-
- // 监听队列
- channel.basicConsume(QUEUE_NAME, false, consumer);
-
- }
-
- }

消费者2
- /**
- * Topic 消费者1
- *
- * @author zhang
- *
- */
- public class TopicRevc2 {
- public static final String TOPIC_NAME = "topic_test";
- public static final String QUEUE_NAME = "topic_queue_2";
-
- public static void main(String[] args) throws IOException, TimeoutException {
-
- // 建立连接
- Connection connection = ConnectHelp.getConnect();
-
- // 建立通道
- final Channel channel = connection.createChannel();
-
- // 声明队列
- channel.queueDeclare(QUEUE_NAME, false, false, false, null);
-
- // 绑定队列
- channel.queueBind(QUEUE_NAME, TOPIC_NAME, "food.#");
- // 每次只接受一个数据
- channel.basicQos(1);
-
- // 获取数据
- DefaultConsumer consumer = new DefaultConsumer(channel) {
- @Override
- public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
- throws IOException {
-
- String msg = new String(body, "utf-8");
- System.out.println("TOP2:" + msg);
- // 可以接受下一个消息
- channel.basicAck(envelope.getDeliveryTag(), false);
- }
- };
-
- // 监听队列
- channel.basicConsume(QUEUE_NAME, false, consumer);
-
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。