消息广播到绑定的队列

参见代码no-spring模块包cn.enjoyedu.exchange.fanout中:

通过测试表明,不管我们如何调整生产者和消费者的路由键,都对消息的接受没有影响。

消费者:

public class Consumer1 {

public static void main(String[] argv) throws IOException,
InterruptedException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");

// 打开连接和创建频道,与发送端一样
Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();

channel.exchangeDeclare(FanoutProducer.EXCHANGE_NAME,
BuiltinExchangeType.FANOUT);
// 声明一个随机队列
String queueName = channel.queueDeclare().getQueue();

//所有日志严重性级别
String[] severities={"error","info","warning"};
for (String severity : severities) {
//关注所有级别的日志(多重绑定)
channel.queueBind(queueName, FanoutProducer.EXCHANGE_NAME,
severity);
}
System.out.println(" [*] Waiting for messages:");

// 创建队列消费者
final Consumer consumerA = 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(" Received " + envelope.getRoutingKey() + "':'" + message + "'");
}
};
channel.basicConsume(queueName, true, consumerA);
}
}

消费者2:

//只关注error级别的日志,然后记录到文件中去
//只关注error级别的日志,然后记录到文件中去。
String severity="test";
channel.queueBind(queueName, FanoutProducer.EXCHANGE_NAME,
severity);

System.out.println(" [*] Waiting for messages......");

生产者:

public class FanoutProducer {

public final static String EXCHANGE_NAME = "fanout_logs";

public static void main(String[] args) throws IOException, TimeoutException {
/**
* 创建连接连接到MabbitMQ
*/
ConnectionFactory factory = new ConnectionFactory();
// 设置MabbitMQ所在主机ip或者主机名
factory.setHost("127.0.0.1");

// 创建一个连接
Connection connection = factory.newConnection();

// 创建一个信道
Channel channel = connection.createChannel();
// 指定转发
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

String queueName = "producer_create";
channel.queueDeclare(queueName,false,false,
false,null);
channel.queueBind(queueName,EXCHANGE_NAME,"test");

//所有日志严重性级别
String[] severities={"error","info","warning"};
for(int i=0;i<3;i++){
String severity = severities[i%3];//每一次发送一条不同严重性的日志

// 发送的消息
String message = "Hello World_"+(i+1);
//参数1:exchange name
//参数2:routing key
channel.basicPublish(EXCHANGE_NAME, severity,
null, message.getBytes());
System.out.println(" [x] Sent '" + severity +"':'"
+ message + "'");
}
// 关闭频道和连接
channel.close();
connection.close();
}

}

消费者1和消费2都能收到所有的消息!!