1、RabbitMQ是一个消息代理。它的核心原理非常简单:接收和发送消息。生产(Producing)意思就是发送。
发送消息的程序就是一个生产者(producer)。我们一般用"P"来表示。
队列(queue)就是邮箱的名称。消息通过你的应用程序和RabbitMQ进行传输,它们能够只存储在一个队列(queue)中。 队列(queue)没有任何限制,你要存储多少消息都可以——基本上是一个无限的缓冲。多个生产者(producers)能够把消息发送给同一个队列,同样,多个消费者(consumers)也能够从同一个队列(queue)中获取数据。我们的大致的设计是这样的:
2、工程搭建,maven依赖
代码:
3、配置
public class RabbitmqConfigure {
//队列名称
public final static String QUEUE_NAME = "hello";
//自动确认消息, false 不自动确认,要手动确认消息
public final static boolean AUTOACK = true;
public final static String HOST = "192.168.174.128";
//用户要提前创建
public final static String PASS_WORD="convict_eva";
public final static String USER_NAME="convict_eva";
// virtual host 要提前创建
public final static String VIRTUAL_HOST="/convict_eva";
}
4、发送消息
public class Send {
public static void main(String[] argv) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(RabbitmqConfigure.HOST);
factory.setPassword(RabbitmqConfigure.PASS_WORD);
factory.setUsername(RabbitmqConfigure.USER_NAME);
//VirtualHost 要在控制台提前创建
factory.setVirtualHost(RabbitmqConfigure.VIRTUAL_HOST);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//定义queue
channel.queueDeclare(RabbitmqConfigure.QUEUE_NAME, false, false, false, null);
for (int i=0;i<10;i++){
String message = "Hello World!"+i;
//发送消息
channel.basicPublish("", RabbitmqConfigure.QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
channel.close();
connection.close();
}
}
5、接收消息
public class Recv {
public static void main(String[] args) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(RabbitmqConfigure.HOST);
factory.setPassword(RabbitmqConfigure.PASS_WORD);
factory.setUsername(RabbitmqConfigure.USER_NAME);
factory.setVirtualHost(RabbitmqConfigure.VIRTUAL_HOST);
//打开connection 和 channel
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//声明要消费的queue。可能消费都先被执行,在消费消息之前要确保queue存在
channel.queueDeclare(RabbitmqConfigure.QUEUE_NAME, false, false, false, null);
System.out.println("Waiting for messages.");
/**
* 接收异步消息回调方法,DefaultConsumer提供一个方法可以缓存发送的消息,直到消息被消费。
*/
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
try {
String message = new String(body, "UTF-8");
System.out.println("Received '" + message + "'");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
channel.basicConsume(RabbitmqConfigure.QUEUE_NAME, RabbitmqConfigure.AUTOACK, consumer);
}
}
官网说明:http://www.rabbitmq.com/tutorials/tutorial-one-java.html
rabbitmq 中文:http://rabbitmq.mr-ping.com/tutorials_with_python/[1]Hello_World.html
工程下载:http://download.csdn.net/detail/convict_eva/9610670