RabbitMQ之四 Routinig

在上篇文章Publish/Subscribe中我們構建了一個簡單的日誌系統,可以將日誌消息廣播給多個消費者。

這這篇文章中我們需要添加一個功能,使得日誌消費者可以訂閱日誌的部分消息,比如我們需要將error的日誌消息記錄到日誌文件中,同時將所有的日誌通過控制檯打印出來。

所謂的綁定(binding)就是一個queue與exchange之間的一種聯繫,即這個queue對特定exchange中的消息感興趣。

比如代碼channel.queueBind(queueName, EXCHANGE_NAME, "");

    /**
     * Bind a queue to an exchange, with no extra arguments.
     * @see com.rabbitmq.client.AMQP.Queue.Bind
     * @see com.rabbitmq.client.AMQP.Queue.BindOk
     * @param queue the name of the queue
     * @param exchange the name of the exchange
     * @param routingKey the routing key to use for the binding
     * @return a binding-confirm method if the binding was successfully created
     * @throws java.io.IOException if an error is encountered
     */
    Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;
這個方法的第三個參數routingKey表示對交換機中的某種規則。routingKey對於fanout這種exchange type來說沒有意義,因爲fanout會將消息廣播給所有的queue(綁定的queue)。

Direct exchange

 上篇文章中的日誌系統將所有的日誌消息廣播給綁定的queue,在這篇文章中,我們需要改造代碼使得可以根據日誌消息的重要性來過濾消息,比如我們希望將特定的error消息寫到硬盤,對於warning或者info的日誌消息不需要記錄都硬盤。

可以使用direct exchange。direct exchange的算法就是根據routing key去匹配對應的binding key的消息。direct exchange的消息模型如下

在上圖中我們可以看到,xechange爲direct的交換機x有兩個queue綁定。一個通過binding key orange綁定,另一個通過black green這兩個binding key來綁定。這種情況下,消息帶有orange將會被分發到第一個queue,消息帶有black或者green將會分發到第二個quue。


當然,我們也可以爲一個bindingkey綁定多個queue,這種情況下,就是exchange type爲direct就跟exchange type爲fanout一樣,會將消息廣播給綁定的queue

調整後的日誌系統消息模型如下

代碼如下:

客戶端EmitLogDirect.java

package org.rabbitmq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class EmitLogDirect {
	private static final String EXCHANGE_NAME = "direct_logs";

	public static void main(String[] argv) throws Exception {

		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		factory.setPort(5672);
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();

		channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
		String reqArgv[] = new String[]{"error","Run. Run. Or it will explode."};
		String severity = getSeverity(reqArgv);
		String message = getMessage(reqArgv);

		channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes("UTF-8"));
		System.out.println(" [x] Sent '" + severity + "':'" + message + "'");

		channel.close();
		connection.close();
	}

	private static String getSeverity(String[] strings) {
		if (strings.length < 1)
			return "info";
		return strings[0];
	}

	private static String getMessage(String[] strings) {
		if (strings.length < 2)
			return "Hello World!";
		return joinStrings(strings, " ", 1);
	}

	private static String joinStrings(String[] strings, String delimiter, int startIndex) {
		int length = strings.length;
		if (length == 0)
			return "";
		if (length < startIndex)
			return "";
		StringBuilder words = new StringBuilder(strings[startIndex]);
		for (int i = startIndex + 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
}

服務端ReceiveLogsDirect.java

package org.rabbitmq;

import java.io.IOException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class ReceiveLogsDirect {
	 private static final String EXCHANGE_NAME = "direct_logs";

	  public static void main(String[] argv) throws Exception {
	    ConnectionFactory factory = new ConnectionFactory();
	    factory.setHost("localhost");
	    factory.setPort(5673);
	    Connection connection = factory.newConnection();
	    Channel channel = connection.createChannel();

	    channel.exchangeDeclare(EXCHANGE_NAME, "direct");
	    String queueName = channel.queueDeclare().getQueue();
	    String[] reqArgv = new String[]{"info","warning","error"};
	    if (reqArgv.length < 1){
	      System.err.println("Usage: ReceiveLogsDirect [info] [warning] [error]");
	      System.exit(1);
	    }

	    for(String severity : reqArgv){
	      channel.queueBind(queueName, EXCHANGE_NAME, severity);
	    }
	    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

	    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");
	        System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
	      }
	    };
	    channel.basicConsume(queueName, true, consumer);
	  }
}
運行結果如下:

參考http://www.rabbitmq.com/tutorials/tutorial-four-java.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章