上一篇文章提到了rabbitMQ的體系結構和一些核心概念,這篇文章就通過一個最簡單的Java版helloWorld實例來看實際代碼中這些概念的體現。
前期準備
1、在自己的電腦上安裝rabbitMQ server
2、下載rabbitMQ 的java API,就是一個jar包,並在工程中導入
introduction
上一篇說到MQ解決的主要問題是降低系統之間、模塊之間的耦合度,在這個層面上,可以將rabbitMQ理解爲一個message broker,producer將message發送給rabbitMQ,rabbitMQ做爲中間方將message傳遞給consumer,從而使producer和consumer之間解耦。message在兩者之間傳遞的時候可以依據相應的規則進行路由,緩存甚至持久化
producer可以簡單理解爲發送消息的程序,在本文的圖像中以下圖代表producer:
queue是模塊間通信的“信箱”,其生命週期只存在於rabbitMQ server中,本質而言,queue就是一個無窮緩衝隊列,一個或者多個producer/consumer都可以無限制的連接上mq,這裏說的無限制是在數量上而言,連接MQ server還是要遵循rabbitMQ各種語言的API的規定。在本文的圖像中以下圖代表queue:
consumer就是連接在MQ上等待傳送過來進行消費的:
note:producer consumer 和queue不一定存在於同一臺機器上,並且在大多數情況下是不在同一臺機器上的。對於大型系統而言,各個模塊很有可能部署在不同機器上,模塊和模塊之間的通信遠比同一臺機器上的模塊之間通信複雜,在實際生產環境中運用MQ也會有各種各樣的問題與挑戰。
傳遞一個最簡單的HelloWorld
這部分我們不去深究rabbitMQ java api的細節,僅僅實現一個簡單的模型
producer將一個message發送到queue中,queue將message傳遞給consumer供其消費。在本篇的程序中consumer僅僅將message打印出來。
直接上代碼
producer的代碼:
public class Sender {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
//create a connection to a server
// The connection abstracts the socket connection, and takes care of protocol version negotiation and
// authentication and so on for us. Here we connect to a broker on the local machine - hence the locallhost.
// If we wanted to connect to a broker on a different machine we'd simply specify its name or IP address here.
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
// Next we create a channel, which is where most of the API for getting things done resides.
Channel channel = connection.createChannel();
// To send, we must declare a queue for us to send to; then we can publish a message to the queue:
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
//publish the message to the queue
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
consumer的代碼:
public class Receiver {
private static final String QUEUE_NAME = "hello";
private static final String HOST_ADDRESS = "localhost";
public static void main(String[] args) throws IOException, TimeoutException {
//Setting up is the same as the sender;
// we open a connection and a channel, and declare the queue from which we're going to consume.
// Note this matches up with the queue that send publishes to.
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(HOST_ADDRESS);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// Note that we declare the queue here, as well.
// Because we might start the receiver before the sender,
// we want to make sure the queue exists before we try to consume messages from it.
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("[*] waiting for message .To exit press CTRL+C");
// We're about to tell the server to deliver us the messages from the queue.
// Since it will push us messages asynchronously, we provide a callback in the form of an object that
// will buffer the messages until we're ready to use them. That is what a DefaultConsumer subclass does.
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body,"UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME,true, consumer);
}
}