生产者:
package com.gavin.mq.fanout;
import com.gavin.utils.RabbitMQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 广播模型:生产者发送到交换机,交换机决定发送到哪个队列,生产者无法决定
* 每个消费者都有自己的队列
* 每个队列都要绑定到交换机
*/
public class WorkProvider {
@Test
public void testSendMessage() throws IOException, TimeoutException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机 参数1:交换机名称
channel.exchangeDeclare("logs","fanout");
channel.basicPublish("logs","", MessageProperties.PERSISTENT_BASIC,("hello work queue").getBytes());
RabbitMQUtils.close(channel,connection);
}
}
消费者:
package com.gavin.mq.fanout;
import com.gavin.utils.RabbitMQUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class WorkConsumer {
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("logs","fanout");
/**
* 临时队列
*/
String tempQueue = channel.queueDeclare().getQueue();
/**
* 绑定交换机和队列
*/
channel.queueBind(tempQueue,"logs","");
channel.basicConsume(tempQueue,true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(new String(body));
}
});
}
}