1.即类似观察者模式,公众号
2.生产者:
public class Send {
private static final String EXCHANGE_NAME = "test_exchange_fanout";
public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(EXCHANGE_NAME,"fanout");//分发
//发送消息
String msg = "hello pa";
channel.basicPublish(EXCHANGE_NAME,"",null,msg.getBytes());
System.out.println("Send:"+msg);
channel.close();
connection.close();
}
}
消息哪去了?? 丢失了!因为交换机没有存储的能力。在rabbitmq里面只有队列有存储能力。
因为这时候还没有队列绑定到这个交换机,所以数据丢失了!
消费者:
Receive1.java
public class Receive1 {
private static final String EXCHANGE_NAME = "test_exchange_fanout";
private static final String QUEUE_NAME = "test_queue_fanout_email";
private static int i = 1;
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
final Channel channel = connection.createChannel();
//队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//绑定队列到交换机/转发器
channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");
//保证一次只分发一个
channel.basicQos(1);
//创建消费者
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
//一旦有消息就会触发这个方法
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String str = new String(body,"utf-8");
System.out.println("[1] receive :"+str+" "+(i++));
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("[1] done ");
//手动回执
channel.basicAck(envelope.getDeliveryTag(),false);
}
}
};
//监听队列 不让其自动应答
channel.basicConsume(QUEUE_NAME,false,defaultConsumer);
}
}
Receive2.java
public class Receive2 {
private static final String EXCHANGE_NAME = "test_exchange_fanout";
private static final String QUEUE_NAME = "test_queue_fanout_sms";
private static int i = 1;
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
final Channel channel = connection.createChannel();
//队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//绑定队列到交换机/转发器
channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");
//保证一次只分发一个
channel.basicQos(1);
//创建消费者
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
//一旦有消息就会触发这个方法
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String str = new String(body,"utf-8");
System.out.println("[2] receive :"+str+" "+(i++));
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("[2] done ");
//手动回执
channel.basicAck(envelope.getDeliveryTag(),false);
}
}
};
//监听队列 不让其自动应答
channel.basicConsume(QUEUE_NAME,false,defaultConsumer);
}
}