RabbitMQ 是一个消息代理。这主要的原理十分简单,就是通过接受和转发消息。RabbitMQ不处理文件,而是接受,并存储和以二进制形式将消息转发。在消息的传送过程中,我们使用一些标准称呼:发送消息的程序就是一个生产者,我们使用“P”来描述它;接收消息的程序是消费者,消费过程与接收相似,一个消费者通常是一个等着接受消息的程序,我们使用"C"来描述。来源:http://blog.youkuaiyun.com/a704755096/article/details/45969717
Java 客户端库 RabbitMQ 遵循AMQP协议,那是一个开放的,并且通用的消息协议。接下来看下java Android RabbitMQ怎么发送和接收消息:
发送端:生产者
- package com.lenovo.app.mq;
- import com.rabbitmq.client.ConnectionFactory;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.Channel;
- public class SendDirect{
- private final static String QUEUE_NAME = "queue";
-
- public static void main(String[] arg) throws java.io.IOException{
-
- 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";
-
- channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
- System.out.println("[Send]" + message );
-
- channel.close();
- connection.close();
- }
- }
接收端:消费者
- package com.lenovo.app.mq;
- import com.rabbitmq.client.ConnectionFactory;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.QueueingConsumer;
- public class ReceiveDirect{
- private final static String QUEUE_NAME = "queue";
-
- public static void main(String[] arg) throws java.io.IOException,
- java.lang.InterruptedException{
-
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost("localhost");factory.setRequestedHeartbeat(2);
-
-
-
-
-
- Connection connection = factory.newConnection();
- Channel channel = connection.createChannel();
-
- channel.queueDeclare(QUEUE_NAME, false, false, false, null);
- System.out.println("Waiting for messages……");
-
-
- 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("[Received]" + message );
- }
-
- }
- }
关闭连接
- private void closeConn(){
- if(connection!=null&&connection.isOpen()){
- try {
- connection.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- isConnect=false;
- }
注意:Android网络连接耗时操作需要在子线程中。RabbitMQ client jar包下载地址:http://download.youkuaiyun.com/download/a704755096/9613612