RabbitMQ - SpringBoot 案例 - topic 模式

HuDu發表於2021-06-08

專案架構如下

RabbitMQ - SpringBoot 案例 - topic 模式

服務層程式碼如下

@Service
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "email.topic.queue",durable = "true",autoDelete = "false"),
        exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
        key = "*.email.#"
))
public class TopicEmailConsumer {
    @RabbitHandler
    public void receiveMessage(String message) {
        System.out.println("email fanout--接收到的訂單資訊是:->" + message);
    }
}

@Service
@RabbitListener(bindings = @QueueBinding(
 value = @Queue(value = "sms.topic.queue",durable = "true",autoDelete = "false"),
  exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
  key = "#.sms.#"
))
public class TopicSMSConsumer {
  @RabbitHandler
  public void receiveMessage(String message) {
  System.out.println("sms fanout--接收到的訂單資訊是:->" + message);
  }
}

@Service
@RabbitListener(bindings = @QueueBinding(
 value = @Queue(value = "weChat.topic.queue",durable = "true",autoDelete = "false"),
  exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
  key = "weChat.#"
))
public class TopicWeChatConsumer {
  @RabbitHandler
  public void receiveMessage(String message) {
  System.out.println("weChat fanout--接收到的訂單資訊是:->" + message);
  }
}

這裡使用的是 RabbitMQ 提供的註解的方式來進行佇列和交換機進行繫結,啟動消費者,可以看到建立了 Topic 型別的交換機,並且進行了交換機的繫結。

RabbitMQ - SpringBoot 案例 - topic 模式

消費者程式碼如下

public void makeOrderTopic(String userId,String productId,int num) {
        // 1:根據id查詢商品是否充足
        // 2:儲存訂單
        String orderId = UUID.randomUUID().toString();
        System.out.println("訂單生成成功:"+orderId);
        // 3:通過 MQ 來完成訊息的分發
        // 交換機,路由 key/queue 佇列名稱,訊息內容
        String exchangeName = "topic_order_exchange";
        String routingKey = "com.email.sms";
        rabbitTemplate.convertAndSend(exchangeName,routingKey,orderId);
    }

RabbitMQ - SpringBoot 案例 - topic 模式

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章