1. 参照上一个例子, 创建一个type是direct的交换机
2. 创建消费者1, 并在消费者中绑定交换机与queue的关系。
public class BiaDu {
public static void main(String[] args) throws IOException {
Connection connection = RabbitUtils.getConnection();
final Channel channel = connection.createChannel();
//channel.queueDeclare("baidu", false, false, false, null);
//queueBind用于将队列与交换机绑定
//参数1:队列名 参数2:交互机名 参数三:路由key
channel.queueBind("baidu", "Allen_Exchange_002", "baidu");
channel.queueBind("baidu", "Allen_Exchange_002", "baidubaike");
channel.basicQos(1);
channel.basicConsume("baidu", false , new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("百度天气收到气象信息:" + new String(body));
channel.basicAck(envelope.getDeliveryTag() , false);
}
});
}
}
2. 创建消费者2, 并在消费者中绑定交换机与queue的关系。
public class BiaDu {
public static void main(String[] args) throws IOException {
Connection connection = RabbitUtils.getConnection();
final Channel channel = connection.createChannel();
//channel.queueDeclare("baidu", false, false, false, null);
//queueBind用于将队列与交换机绑定
//参数1:队列名 参数2:交互机名 参数三:路由key
channel.queueBind("baidu", "Allen_Exchange_002", "baidu");
channel.queueBind("baidu", "Allen_Exchange_002", "baidubaike");
channel.basicQos(1);
channel.basicConsume("baidu", false , new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("百度天气收到气象信息:" + new String(body));
channel.basicAck(envelope.getDeliveryTag() , false);
}
});
}
}
3. 创建生产者
public class WeatherBureau {
public static void main(String[] args) throws Exception {
Map area = new LinkedHashMap<String, String>();
area.put("baidu", "百度-中国湖南长沙天气数据");
area.put("sina", "新浪-中国湖北武汉天气数据");
area.put("baidubaike", "百度-中国湖南株洲天气数据");
area.put("sinaweibo", "新浪-中国湖北武汉天气数据");
Connection connection = RabbitUtils.getConnection();
Channel channel = connection.createChannel();
Iterator<Map.Entry<String, String>> itr = area.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String, String> me = itr.next();
//第一个参数交换机名字 第二个参数作为 消息的routing key
channel.basicPublish("Allen_Exchange_002",me.getKey() , null , me.getValue().getBytes());
}
channel.close();
connection.close();
}
}
启动消费者1和消费者2
启动生产者
执行结果: