本文是笔者阅读官方文档之后所写的一些读后感和记录,在进入本文之前,我想说一下学习最好的地方之一还是去相应的官网Get Started.那里有比较官方和正确的说明:http://www.rabbitmq.com/getstarted.html.本文将使用java语言作为演示.
下载与安装rabbit和erlang:
rabbit:http://www.rabbitmq.com/download.html
erlang:http://www.erlang.org/downloads
下载安装之后,rabbit server如下如所示:
其中,在sbin目录下有rabbitmq-server,rabbitmq-plugins,rabbitmq-service等批处理文件.
rabbitserver的默认监听端口是5672.
启动rabbit server:
打开cmd,进入sbin目录下:开启rabbit 的插件:rabbitmq-plugins enable rabbitmq_management
执行sbin下的rabbitmq-server.bat启动rabbit:
在浏览器中输入:http://localhost:15672,此时会进入rabbit的登录界面:输入guest/guest进行登录
切换到queues队列视图:新建一个hello队列:
java api
1.引入jar包
amqp-client-4.0.2.jar
slf4j-api-1.7.21.jar
slf4j-simple-1.7.22.jar
2.代码
Sending:
package yzr.main;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class sender {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//it will only be created if it doesn't exist already
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
Receiving
package yzr.main;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.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);
}
}
测试: