1. 程式人生 > >RabbitMQ學習(三)訂閱/發布

RabbitMQ學習(三)訂閱/發布

cto submit actor nal chan true exec oid lsp

RabbitMQ學習(三)訂閱/發布

1.RabbitMQ模型

技術分享

前面所學都只用到了生產者、隊列、消費者。如上圖所示,其實生產者並不直接將信息傳輸到隊列中,在生產者和隊列中間有一個交換機(Exchange),我們之前沒有使用到交換機是應為我們沒有配置交換機,使用了默認的交換機。

有幾個可供選擇的交換機類型:直連交換機(direct), 主題交換機(topic), (頭交換機)headers和 扇型交換機(fanout)

這裏我們使用扇形交換機做一個簡單的廣播模型:一個生產者和多個消費者接受相同消息;

生產者代碼:

public class Productor {
public static void

main(String[] args) throws IOException, TimeoutException {
//配置rabbitmq服務器地址
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(5672);
factory.setUsername("starktan");
factory.setPassword("starktan"
);
factory.setVirtualHost("/");
//建立連接和通道
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//聲明一個扇形交換機
channel.exchangeDeclare("fanout", BuiltinExchangeType.FANOUT);
System.out.println("
發送信息!");
String message = "WorkQueue Message number " + System.currentTimeMillis();
channel.basicPublish("fanout", "", true, null, message.getBytes());
channel.close();
connection.close();
}
}

消費者代碼:

public class Consumer {
public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {
//創建連接和通道
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
final Connection connection = factory.newConnection();
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 4; i++) {
final int cur = i;
service.submit(new Runnable() {
Channel channel = connection.createChannel();
String queryname = channel.queueDeclare().getQueue();
public void run() {
//創建隊列消費者
QueueingConsumer consumer = new QueueingConsumer(channel);
try {
channel.queueBind(queryname,"fanout","");
channel.basicConsume(queryname,consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println("線程 " + cur + " 獲取到消息 " + message);

}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
service.shutdown();
}
}

運行效果:

技術分享

RabbitMQ學習(三)訂閱/發布