标签:style blog http io color ar os sp java
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项。)
标签:style blog http io color ar os sp java
原文地址:http://www.cnblogs.com/alvez/p/4100070.html