天天看點

SpringAMQP 釋出訂閱-DirectExchange

Direct Exchange 會将接收到的消息根據規則路由到指定的Queue,是以稱為路由模式(routes)。

  • 每一個Queue都與Exchange設定一個BindingKey
  • 釋出者發送消息時,指定消息的RoutingKey
  • Exchange将消息路由到BindingKey與消息RoutingKey一緻的隊列

DirectExchange的使用

  • 在consumer服務中,編寫兩個消費者方法,分别監聽direct.queue1和direct.queue2
    • 利用@RabbitListener聲明Exchange、Queue、BindingKey
  • 在publisher中編寫測試方法
    • 向指定Exchange和RoutingKey(RoutingKey就是BindingKey)發送消息

在consumer服務中,編寫兩個消費者方法

@RabbitListener(bindings = @QueueBinding(
            value = @Queue("direct.queue1"),
            exchange = @Exchange("marw.direct"),
            key={"red","blue"}
            ))
    public void listenDirectQueue1(String msg) throws InterruptedException {
        System.out.println("listenDirectQueue1 消費者接收到消息 :【" + msg + "】");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("direct.queue2"),
            exchange = @Exchange("marw.direct"),
            key={"red","yellow"}
    ))
    public void listenDirectQueue2(String msg) throws InterruptedException {
        System.err.println("listenDirectQueue2 消費者接收到消息 :【" + msg + "】");
    }      

@Test
    public void testDirectQueue() throws InterruptedException {
        String queueName = "marw.direct";
        String message = "hello, Direct queue message";
        rabbitTemplate.convertAndSend(queueName, "red", message);
    }      

繼續閱讀