Loading

RabbitMQ:Direct Exchange

一.相关概念

Exchange:接收消息,并根据路由键转发消息到所绑定的队列。

属性:

  name:名称

  type:交换机类型direct/topic/fanout/headers

  durability:是否需要持久化

  auto delete:当最后一个绑定到Exchange上的队列删除后,自动删除该Exchange

  internal:当前Exchange是否用于RabbitMQ内部使用,默认为false

  Arguments:扩展参数,用于扩展AMQP协议自制使用。

二.Direct Exchange

所有发送到Direct Exchange的消息会被转发到RoutingKey中指定的QUEUE.

注意:Direct模式使用RabbitMQ自带的Exchange:Default Exchange,所以不需要将Exchange进行任何绑定操作。队列名和routingkey必须完全匹配,消息才能被队列接收。

三.消费者

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //创建一个连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.10.132");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //创建连接
        Connection connection = connectionFactory.newConnection();
        //通过连接创建一个Channel
        Channel channel = connection.createChannel();
        //创建一个队列
        String exchangeName = "test_direct_exchange";
        String exchangeType = "direct";
        String queueName = "direct";
        String routingKey = "test.direct";
        String routingKey2 = "direct";
        //声明一个交换机
        channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);
        //声明一个队列
        channel.queueDeclare(queueName,false,false,false,null);
        //建立绑定关系
        channel.queueBind(queueName,exchangeName,routingKey);
        channel.queueBind(queueName,exchangeName,routingKey2);
        //创建一个消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //设置Channel
        channel.basicConsume(queueName,true,consumer);
        //获取消息
        while (true){
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消费端:"+msg);
        }

    }

四.生产者

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建一个连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.10.132");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //创建连接
        Connection connection = connectionFactory.newConnection();
        //通过连接创建一个Channel
        Channel channel = connection.createChannel();
        //通过Channel发送数据
        channel.basicPublish("test_direct_exchange","direct",null,"test direct exchange".getBytes());
        //关闭连接
        channel.close();
        connection.close();
    }

 关系拓扑:

 

 生产者设置routingKey无论传direct或者传test.direct,都可以给消费者发送信息。但是设置其他的,消费者都无法接收消息。

posted @ 2020-05-27 16:29  秋风飒飒吹  阅读(361)  评论(0编辑  收藏  举报