密云区免费网站建设,大型网站制作平台,郑州高端网站定制,东莞网络推广公司路由模式 队列与交换机的绑定#xff0c;不能是任意绑定了#xff0c;而是要指定一个 RoutingKey#xff08;路由key#xff09;
消息的发送方在向 Exchange 发送消息时#xff0c;也必须指定消息的 RoutingKey
Exchange 不再把消息交给每一个绑定的队列#xff0c;而是…路由模式 队列与交换机的绑定不能是任意绑定了而是要指定一个 RoutingKey路由key
消息的发送方在向 Exchange 发送消息时也必须指定消息的 RoutingKey
Exchange 不再把消息交给每一个绑定的队列而是根据消息的 Routing Key 进行判断只有队列的 Routingkey 与消息的 Routing key 完全一致才会接收到消息
生产者代码
public class RouteProducer {public static void main(String[] args) throws Exception {//1.创建连接ConnectionFactory cf new ConnectionFactory();cf.setHost(192.168.64.140);cf.setPort(5672);cf.setUsername(guest);cf.setPassword(guest);Connection nc cf.newConnection();Channel cc nc.createChannel();//2.定义交换机cc.exchangeDeclare(direct_logs, BuiltinExchangeType.DIRECT);//3.发送数据携带路由键while(true) {Scanner scanner new Scanner(System.in);System.out.print(消息);String s scanner.nextLine();System.out.print(路由键);String key scanner.nextLine(); cc.basicPublish(direct_logs, key, null, s.getBytes()) System.out.println(-----------------------------------------------------);} }
}消费者代码
public class RouteConsumer {public static void main(String[] args) throws Exception {//1.创建连接ConnectionFactory cf new ConnectionFactory();cf.setHost(192.168.64.140);cf.setPort(5672);cf.setUsername(guest);cf.setPassword(guest);Connection nc cf.newConnection();Channel cc nc.createChannel();//2.定义交换机cc.exchangeDeclare(direct_logs, BuiltinExchangeType.DIRECT);/3.定义队列String queue cc.queueDeclare().getQueue();//4.绑定队列和交换机(重复绑定多次)System.out.print(输入绑定键用空格隔开);String s new Scanner(System.in).nextLine();//aaa bbb cccString[] a s.split(\\s);for (String key : a) {ch.queueBind(queue, direct_logs, key);}//5.处理数据DeliverCallback deliverCallback new DeliverCallback() {Overridepublic void handle(String consumerTag, Delivery message) throws IOException {//从message中取出消息和路由键String snew String(message.getBody());String key message.getEnvelope().getRoutingKey();System.out.println(s--key);System.out.println();}};CancelCallback cancelCallback new CancelCallback() {Overridepublic void handle(String consumerTag) throws IOException {}};cc.basicConsume(queue, true,deliverCallback,cancelCallback);}
}上一篇文章https://blog.csdn.net/Z0412_J0103/article/details/143354922https://blog.csdn.net/Z0412_J0103/article/details/143354922下一篇文章