目的:producer的消息要分发到指定的消息队列
如上图。当前exchange的类型是:direct的。当发送的消息的exchangeKey为error的,两个消息队列都会收到消息。当exchangeKey为info的,则只有下面那么消息队列收到消息。综上所述,RabbitMQ的路由实现是通过exchangeKey来实现的
实现代码如下:
生产者:EmitLogDirect.java
package yy.rabbitstudy.routing;
import java.io.IOException;
import org.springframework.amqp.core.ExchangeTypes;
import com.rabbitmq.client.Channel;
import yy.rabbitstudy.util.RabbitMQUtil;
public class EmitLogDirect {
private static final String EXCHANGE_NAME = "direct_logs";
public static void main(String[] args) {
args=new String[]{"error","info","error","warning"};
Channel channel = RabbitMQUtil.getChannel();
try {
//ExchangeTypes的类型是Direct
channel.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.DIRECT);
for (String exchangeKey : args) {
String string=exchangeKey;
//路由的路径是exchangeKey
channel.basicPublish(EXCHANGE_NAME, exchangeKey, null, string.getBytes());
}
System.out.println("send end");
} catch (IOException e) {
e.printStackTrace();
}finally {
RabbitMQUtil.close();
}
}
}
消费者:ReceiveLogsDirect.java
package yy.rabbitstudy.routing;
import java.io.IOException;
import org.springframework.amqp.core.ExchangeTypes;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP.BasicProperties;
import yy.rabbitstudy.util.RabbitMQUtil;
public class ReceiveLogsDirect {
private static final String EXCHANGE_NAME = "direct_logs";
public static void main(String[] args) {
System.out.println("I'am Consumer A");
args=new String[]{"info","error","warning"};
/* System.out.println("I'am Consumer B");
args=new String[]{"error"};*/
Channel channel = RabbitMQUtil.getChannel();
try {
channel.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.DIRECT);
String queueName=channel.queueDeclare().getQueue();
for (String exchangeKey : args) {
//绑定Exchange的同时也设置exchangeKey
channel.queueBind(queueName, EXCHANGE_NAME, exchangeKey);
}
Consumer consumer=new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, 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);
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
消费者C1:
I'am Consumer B
[x] Received 'error':'error'
[x] Received 'error':'error'
消费者C2
I'am Consumer A
[x] Received 'error':'error'
[x] Received 'info':'info'
[x] Received 'error':'error'
[x] Received 'warning':'warning'