RabbitMQ學習(三)訂閱/發布
阿新 • • 發佈:2017-07-13
cto submit actor nal chan true exec oid lsp
RabbitMQ學習(三)訂閱/發布
1.RabbitMQ模型
前面所學都只用到了生產者、隊列、消費者。如上圖所示,其實生產者並不直接將信息傳輸到隊列中,在生產者和隊列中間有一個交換機(Exchange),我們之前沒有使用到交換機是應為我們沒有配置交換機,使用了默認的交換機。
有幾個可供選擇的交換機類型:直連交換機(direct), 主題交換機(topic), (頭交換機)headers和 扇型交換機(fanout)
這裏我們使用扇形交換機做一個簡單的廣播模型:一個生產者和多個消費者接受相同消息;
生產者代碼:
public class Productor { //配置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 { |
運行效果:
RabbitMQ學習(三)訂閱/發布