rabbitmq Introduction one "hello world"

转载自:http://www.rabbitmq.com/tutorials/tutorial-one-java.html

RabbitMQ is a message broker[代理]. In essence[本质上], it accepts messages from producers, and delivers them toconsumers. In-between, it can  route, buffer, and persist the messages according to rules you give it.

RabbitMQ, and messaging in general, uses some jargon[术语].

Producing means nothing more than[不过是,无非是] sending. A program that sends messages is a producer. We'll draw it like that, with "P":

A queue is the name for a mailbox[邮箱,信箱]. It lives inside RabbitMQ. Although messages flow through[流过] RabbitMQ and your applications, they can be stored only inside aqueue[它们只能存储在queue中]. A queue is not bound by any limits[队列是不受任何限制], it can store as many messages as you like - it's essentially[本质上] an infinite[无限的,无穷的] buffer. Many producers can send messages that go to one queue - many consumers can try to receive data from onequeue. A queue will be drawn like this, with its name above it:

Consuming has a similar meaning to receiving. Aconsumer is a program that mostly waits to receive messages. On our drawings it's shown with "C":

Note that the producer, consumer, and broker do not have to reside[驻留] on the same machine; indeed[的确] in most applications they don't.


"Hello World"

(using the Java Client)

In this part of the tutorial[辅导的] we'll write two programs in Java; a producer that sends a single message, and a consumer that receives messages and prints them out. We'll gloss over[掩盖,掩饰] some of the detail in the Java API, concentrating[集中] on this very simple thing just to get started. It's a "Hello World" of messaging.

In the diagram[图表] below, "P" is our producer and "C" is our consumer. The box in the middle is a queue - a message buffer that RabbitMQ keeps on behalf[代表] of the consumer.

(P) -> [|||] -> (C)

The Java client library

RabbitMQ speaks AMQP, which is an open,general-purpose[多用途的,一般用途的] protocol for messaging. There are a number of clients for AMQP in many different languages. We'll use the Java client provided by RabbitMQ.

Download the client library package, and check its signature[签名] as described. Unzip it into your working directory and grab  the JAR files from the unzipped directory:

$ unzip rabbitmq-java-client-bin-*.zip
$ cp rabbitmq-java-client-bin-*/*.jar ./

(The RabbitMQ Java client is also in the central Maven repository,with the groupIdcom.rabbitmq and the artifactIdamqp-client.)

Now we have the Java client and its dependencies, we can write somecode.

Sending

(P) -> [|||]

We'll call our message sender Send and our message receiver Recv. The sender will connect to RabbitMQ, send a single message,then exit.

InSend.java,we need some classes imported:

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

Set up the class and name the queue:

public class Send {

  private final static String QUEUE_NAME = "hello";

  public static void main(String[] argv)
      throws java.io.IOException {
      ...
  }
}

then we can create a connection to the server:

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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 localhost. If we wanted to connect to a broker on a different machine we'd simply specify its name or IP address here.

Next we create a channel, which is where most of the API for gettingthings done resides.

To send, we must declare a queue for us to send to; then we can publish a messageto the queue:

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

Declaring a queue is idempotent[幂等的] - it will only be created if it doesn't exist already. The message content is a byte array, so you can encode[编码] whatever you like there.

Lastly, we close the channel and the connection;

    channel.close();
    connection.close();

Here's the whole Send.javaclass.

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

public class Send {

  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);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");
    
    channel.close();
    connection.close();
  }
}

Sending doesn't work!

If this is your first time using RabbitMQ and you don't see the "Sent"message then you may be left scratching[挠头] your head wondering what could be wrong. Maybe the broker was started without enough free disk space(by default it needs at least 1Gb free) and is therefore refusing to accept messages. Check the broker logfile to confirm and reduce the limit if necessary. Theconfiguration file documentation will show you how to set disk_free_limit.



Receiving

That's it for our sender. Our receiver is pushed[推送] messages from RabbitMQ, so unlike[和..不同] the sender which publishes a single message, we'll keep it running to listen for messages and print them out.

[|||] -> (C)

The code (in Recv.java) has almost the same imports as Send:

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;

public class Recv {

    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);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    
    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 + "'");
    }
  }
}


import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;

The extra Queueing Consumer is a class we'll use to buffer the messages pushed to us by the server.

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.

public class Recv {

  private final static String QUEUE_NAME = "hello";

  public static void main(String[] argv)
      throws java.io.IOException,
             java.lang.InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    ...
    }
}

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.

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 Queueing Consumer does.

    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 + "'");
    }

QueueingConsumer.nextDelivery() blocks until another message has been delivered from the server.

Here's the whole Recv.java class.

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;

public class Recv {

    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);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    
    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 + "'");
    }
  }
}

Putting it all together

You can compile both of these with just the RabbitMQ java client onthe classpath:

$ javac -cp rabbitmq-client.jar Send.java Recv.java

To run them, you'll need rabbitmq-client.jar and its dependencies on the classpath. In a terminal, run the sender:

$ java -cp .:commons-io-1.2.jar:commons-cli-1.1.jar:rabbitmq-client.jar Send

then, run the receiver:

$ java -cp .:commons-io-1.2.jar:commons-cli-1.1.jar:rabbitmq-client.jar Recv

On Windows, use a semicolon[分号] instead of a colon[冒号] to separate items in the classpath.

The receiver will print the message it gets from the sender via RabbitMQ. The receiver will keep running, waiting for messages (Use Ctrl-C to stop it), so try running the sender from another terminal.

If you want to check on the queue, try using rabbitmqctl list_queues.

Hello World!

Time to move on to part 2 and build a simple work queue.

Hint[提示]

To save typing, you can set an environment variable for the classpath e.g.

 $ export CP=.:commons-io-1.2.jar:commons-cli-1.1.jar:rabbitmq-client.jar
 $ java -cp $CP Send

or on Windows:

 > set CP=.;commons-io-1.2.jar;commons-cli-1.1.jar;rabbitmq-client.jar
 > java -cp %CP% Send





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值