RabbitMQ是個健壯、易用、開源、支持多種操作系統和語言的message broker。
當然,一切的前提是機器里面正在運行著rabbitmq-server。
點擊下面的圖片下載:
rabbitMQ和AMQP的關系是什么樣的?rabbitMQ負責哪部分?如圖所示,就是PRovider和consumer之間那一塊。
message broker,比如ActiveMQ、RabbitMQ什么的,簡單而言就是可以收發消息的。
我跟著官方的Tutorial簡單寫一個Hello World。實現一個producer到queue到consumer的小程序。

不要忘了添加java client :
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.3.4</version></dependency>
provider:
private final static String QUEUE_NAME = "hello"; public static void main(String[] args) throws IOException { //創建Connection ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); //定義目標隊列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World!"; System.out.println(" [x] Sent '" + message + "'"); channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); channel.close(); connection.close(); }Receiver的步驟與provider大致相同,只需要注意QUEUE_NAME要相同:
private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'" + new Date()); }}如果不出意外的話,consumer可以正常打印出"Hello World!"。(PS:磁盤太滿也可能導致消息無法接收,可以在配置文件中設置disk_free_limit項。)
新聞熱點
疑難解答