一个生产者,一个交换机,两个队列,两个消费者
声明一个Fanout类型的exchange,并且将exchange和queue绑定在一起,绑定的方式就是直接绑定。
让生产者创建一个exchange并且指定类型,和一个或多个队列绑定到一起。
public class PSTest {
@Test
public void pubTest() throws IOException {
Connection connection = MQFactory.getConnection();
Channel channel = connection.createChannel();
//创建交换机 指定类型为fanout
channel.exchangeDeclare("ps_exchange", BuiltinExchangeType.FANOUT);
//创建队列
channel.queueDeclare("ps_queue1",true,false,false,null);
channel.queueDeclare("ps_queue2",true,false,false,null);
//交换机跟队列绑定
channel.queueBind("ps_queue1","ps_exchange","");
channel.queueBind("ps_queue2","ps_exchange","");
for (int i = 0; i < 10; i++) {
channel.basicPublish("ps_exchange","",null,("msg:"+i).getBytes());
}
}
@Test
public void conTest() throws IOException {
Connection connection = MQFactory.getConnection();
Channel channel = connection.createChannel();
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String s = new String(body, "utf-8");
System.out.println("消费者1:" + s);
}
};
channel.basicConsume("ps_queue1",true,defaultConsumer);
System.in.read();
}
@Test
public void conTest1() throws IOException {
Connection connection = MQFactory.getConnection();
Channel channel = connection.createChannel();
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String s = new String(body, "utf-8");
System.out.println("消费者2:" + s);
}
};
channel.basicConsume("ps_queue2",true,defaultConsumer);
System.in.read();
}
}
交换机分别发给两个队列