消息中间件RabbitMQ系列,路由模型Routing,提供者和消费者(十)

it2026-01-04  9

前面我们已经讲了我们创建交换机的时候,有很多的模型,之前已经讲了广播模型,现在开始讲路由模型

也就是现在增加了一个路由key,消息里面要有路由key ,队列里面要有路由key,

路由key就起到关键的作用,现在就可以利用路由key来决定哪些消息在哪些队列里面。

提供者

public class Provider { public static void main(String[] args) throws IOException { Connection connection = RabbitMqUtils.getConnection(); // 创建通道 Channel channel = connection.createChannel(); // 将通道声明指定的交换机 参数1:交换机的名称 参数2:交换机的类型 direct 路由模式 channel.exchangeDeclare("logs","direct"); // 发送消息 String routinkey = "info"; channel.basicPublish("logs",routinkey,null,("这个是路由key发送的消息").getBytes()); // 释放资源 RabbitMqUtils.closeConnectionAndChannel(channel,connection); } }

提供者直接创建direct类型的交换机,并且在这个交换机里面放加了路由KEY的信息

消费者

既然已经有了交换机,那么现在就创建消费者来消费交换机里面的信息

public class Customer { public static void main(String[] args) throws IOException { Connection connection = RabbitMqUtils.getConnection(); // 创建通道 Channel channel = connection.createChannel(); // 将通道声明指定的交换机 参数1:交换机的名称 参数2:交换机的类型 fanout 广播类型 channel.exchangeDeclare("logs","direct"); // 创建临时队列 String queue = channel.queueDeclare().getQueue(); // 绑定交换机和队列,意思是交换机里面信息有error这个路由,队列里面也有这个error路由,消费者才可以消费 channel.queueBind(queue,"logs","error"); // 消费消息 channel.basicConsume(queue,true,new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("消费者1:"+new String(body)); } }); } }
最新回复(0)