Java使用RabbitMQ(八)--Topics

topics使用
虽然上一篇的direct交换机改善了我们的系统,但是它依然有限制–不能处理在复杂条件下的路由分发。比如同时根据 日志重要级别和角色来获取。

所以这里介绍另一个复杂点的交换机 topic。
topic交换机也是通过 routing_key 来筛选信息的,routing_key 的格式有要求,用.分隔,*表示一个词,#表示多个词。

这里写图片描述

quick.orange.rabbit会被 q1 q2队列同时收到
lazy.pink.rabbit会被q2收到

生产者:

 public static void main(String[] args) {
        try(Connection connection=getConnection("guest","guest","localhost",5672,"/");
            Channel channel=connection.createChannel()) {

            channel.exchangeDeclare(args[0],"topic");
//            String queueName= channel.queueDeclare().getQueue();
//            System.out.println(queueName);
            String message=getMessage(new String[]{"a","b","c"});
//            String queueName2= channel.queueDeclare().getQueue();
//            System.out.println(queueName2);
//            channel.queueBind(queueName2,args[0],args[1]);
//            channel.queueBind(queueName,args[0],"blue");
            int i=0;
            while (true){
                Thread.sleep(1000);
//                channel.basicPublish(args[0],queueName, null,(i+++message).getBytes("utf-8"));
                channel.basicPublish(args[0],"a.b.c", null,(i+++message).getBytes("utf-8"));
            }

//            Thread.sleep(2000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

消费者:

  public static void main(String[] args) {
        try(Connection connection=BaseTest2.getConnection("guest","guest","localhost",5672,"/");
            Channel channel=connection.createChannel()) {
            channel.exchangeDeclare(args[0],"topic");
//            channel.queueDeclare("red",false,false,false,null);
            String queueName= channel.queueDeclare().getQueue();
            channel.queueBind(queueName,args[0],"a.#");
//            System.out.println(queueName);
            Consumer consumer=new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    try {
                        doWork(message);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        System.out.println(message+" [x] Done");
                    }
//                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            };
            channel.basicConsume(queueName,true, consumer);
            Thread.sleep(200000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
阅读更多

没有更多推荐了,返回首页