Rabbitmq基本操作

  消息代理(message broker), 为应用之间或者应用的不同组件之间的通信- building integration, 

  语言:Erlang

  角色:producer,consumer (消息的发送和接收方)

  应用:点对点通信,订阅/推送

  消息:携带序号,consumer将从独立线程中获得消息

 

抽象类 EndPoint

  producer,consumer统一为 EndPoints 类型的 queue,连接队列的代码也一致 

 1 package co.syntx.examples.rabbitmq;
 2 
 3 import java.io.IOException;
 4 
 5 import com.rabbitmq.client.Channel;
 6 import com.rabbitmq.client.Connection;
 7 import com.rabbitmq.client.ConnectionFactory;
 8 
 9 /**
10  * Represents a connection with a queue
11  * @author syntx
12  *
13  */
14 public abstract class EndPoint{
15     
16     protected Channel channel;
17     protected Connection connection;
18     protected String endPointName;
19     
20     public EndPoint(String endpointName) throws IOException{
21          this.endPointName = endpointName;
22         
23          //Create a connection factory
24          ConnectionFactory factory = new ConnectionFactory();
25         
26          //hostname of your rabbitmq server
27          factory.setHost("localhost");
28         
29          //getting a connection
30          connection = factory.newConnection();
31         
32          //creating a channel
33          channel = connection.createChannel();
34         
35          //declaring a queue for this channel. If queue does not exist,
36          //it will be created on the server.
37          channel.queueDeclare(endpointName, false, false, false, null);
38     }
39     
40     
41     /**
42      * Close channel and connection. Not necessary as it happens implicitly any way. 
43      * @throws IOException
44      */
45      public void close() throws IOException{
46          this.channel.close();
47          this.connection.close();
48      }
49 }
连接和关闭队列

 

The producer  

  把可序列化的Java对象转换成 byte 数组

 1 package co.syntx.examples.rabbitmq;
 2 
 3 import java.io.IOException;
 4 import java.io.Serializable;
 5 
 6 import org.apache.commons.lang.SerializationUtils;
 7 
 8 
 9 /**
10  * The producer endpoint that writes to the queue.
11  * @author syntx
12  *
13  */
14 public class Producer extends EndPoint{
15     
16     public Producer(String endPointName) throws IOException{
17         super(endPointName);
18     }
19 
20     public void sendMessage(Serializable object) throws IOException {
21         channel.basicPublish("",endPointName, null, SerializationUtils.serialize(object));
22     }    
23 }
生产者代码

 

The consumer

  可以以线程方式运行,对于不同的事件有不同的回调函数。

 1 package co.syntx.examples.rabbitmq;
 2 
 3 import java.io.IOException;
 4 import java.util.HashMap;
 5 import java.util.Map;
 6 
 7 import org.apache.commons.lang.SerializationUtils;
 8 
 9 import com.rabbitmq.client.AMQP.BasicProperties;
10 import com.rabbitmq.client.Consumer;
11 import com.rabbitmq.client.Envelope;
12 import com.rabbitmq.client.ShutdownSignalException;
13 
14 
15 /**
16  * The endpoint that consumes messages off of the queue. Happens to be runnable.
17  * @author syntx
18  *
19  */
20 public class QueueConsumer extends EndPoint implements Runnable, Consumer{
21     
22     public QueueConsumer(String endPointName) throws IOException{
23         super(endPointName);        
24     }
25     
26     public void run() {
27         try {
28             //start consuming messages. Auto acknowledge messages.
29             channel.basicConsume(endPointName, true,this);
30         } catch (IOException e) {
31             e.printStackTrace();
32         }
33     }
34 
35     /**
36      * Called when consumer is registered.
37      */
38     public void handleConsumeOk(String consumerTag) {
39         System.out.println("Consumer "+consumerTag +" registered");        
40     }
41 
42     /**
43      * Called when new message is available.
44      */
45     public void handleDelivery(String consumerTag, Envelope env,
46             BasicProperties props, byte[] body) throws IOException {
47         Map map = (HashMap)SerializationUtils.deserialize(body);
48         System.out.println("Message Number "+ map.get("message number") + " received.");
49         
50     }
51 
52     public void handleCancel(String consumerTag) {}
53     public void handleCancelOk(String consumerTag) {}
54     public void handleRecoverOk(String consumerTag) {}
55     public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {}
56 }
消费者代码

 

实际测试

  先运行消费者线程,产生大量消息后被消费者取走

 1 package co.syntx.examples.rabbitmq;
 2 
 3 import java.io.IOException;
 4 import java.sql.SQLException;
 5 import java.util.HashMap;
 6 
 7 public class Main {
 8     public Main() throws Exception{
 9         
10         QueueConsumer consumer = new QueueConsumer("queue");
11         Thread consumerThread = new Thread(consumer);
12         consumerThread.start();
13         
14         Producer producer = new Producer("queue");
15         
16         for (int i = 0; i < 100000; i++) {
17             HashMap message = new HashMap();
18             message.put("message number", i);
19             producer.sendMessage(message);
20             System.out.println("Message Number "+ i +" sent.");
21         }
22     }
23     
24     /**
25      * @param args
26      * @throws SQLException 
27      * @throws IOException 
28      */
29     public static void main(String[] args) throws Exception{
30       new Main();
31     }
32 }

 

posted on 2016-06-02 15:01  Alice&Bob  阅读(1030)  评论(0)    收藏  举报

导航