1. 程式人生 > 實用技巧 >SpringBoot---RabbitMQ訊息佇列_3(Routing模式、萬用字元模式)

SpringBoot---RabbitMQ訊息佇列_3(Routing模式、萬用字元模式)

Routing模式則可以指定具體的接收佇列。

1、在服務類中,編寫路由模式訊息的接收程式碼

@Service
public class MessageService {
//路由模式訊息接收,處理error級別日誌訊息
@RabbitListener(bindings=@QueueBinding(value=@Queue("routing_queue_error"),
                                        exchange = @Exchange(value = "routing_exchange",
                                        type
="direct"),key="error_routing_key")) public void routingConsumerError(String message){ System.out.println("接收到error級別的日誌訊息"+message); }
//路由模式訊息接收,處理info、error、warning級別日誌訊息 @RabbitListener(bindings
= @QueueBinding(value = @Queue("routing_queue_all"), exchange = @Exchange(value ="routing_exchange",type = "direct"),key = {"error_routing_key",
"info_routing_key","warning_routing_key"})) public void routingConsumeAll(String message){ String msg="接收到info、error、warning等級別的日誌訊息:"; System.out.println(msg+message); } }

2、在測試類中添加發送訊息的程式碼,在函式中指定接收的訊息佇列。


@Test
public void adminRabbitMq(){
//1、建立一個交換器
amqpAdmin.declareExchange(new FanoutExchange("my_fanout_exchange"));
//2、建立佇列
amqpAdmin.declareQueue(new Queue("queue_email"));
amqpAdmin.declareQueue(new Queue("queue_sms"));
//3、繫結交換器和佇列
amqpAdmin.declareBinding(new Binding("queue_email",Binding.DestinationType.QUEUE,"my_fanout_exchange","",null));
amqpAdmin.declareBinding(new Binding("queue_sms",Binding.DestinationType.QUEUE,"my_fanout_exchange","",null));
System.out.println("訊息佇列建立成功!");
}

   @Test
public void routingPublisher(){ rabbitTemplate.convertAndSend("routing_exchange","error_routing_key","routing send error message"); System.out.println("訊息傳送成功~"); }

3、完成測試

萬用字元模式

路由模式需要指定接收佇列的名稱,而統配模式可以認為是路由模式的擴充套件,支援佇列名稱的匹配模式。

1、在Service類中新增萬用字元模式的接收方法。

@Service
public class MessageService {
  //萬用字元模式訊息接收,進行郵件業務訂閱處理   @RabbitListener(bindings
= @QueueBinding(value = @Queue("topic_queue_email"), exchange = @Exchange(value = "topic_exchange",type="topic"),key="info.#.email.#"))   public void topicConsumerEmail(String message){   System.out.println("接收到郵件訂閱需求處理訊息:"+message);   }
  //萬用字元模式訊息接收,進行簡訊業務訂閱處理 @RabbitListener(bindings
= @QueueBinding(value = @Queue("topic_queue_sms"), exchange = @Exchange(value = "topic_exchange",type="topic"),key="info.#.sms.#")) public void topicConsumerSms(String message){ System.out.println("接收到簡訊訂閱需求處理訊息:"+message); } }

2、在測試類中添加發送訊息的程式碼,在函式中指定接收的訊息佇列。

@Test
public void topicPublisher(){
rabbitTemplate.convertAndSend("topic_exchange","info.email.sms","topic send email and sms message");
}

3、完成測試