前端时间更新了mac下面安装rabbitmq 下面介绍一下使用这个mq的教程。
首先,打开mq的官网。找到Java的用例。然后试了一下,成功了。
http://www.rabbitmq.com/tutorials/tutorial-one-java.html
main方法方式用例
package org.young.common.test;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* Created by young on 16/10/7.
*/
public class Send {
private final static String QUEUE_NAME = "mq.queue";
public static void main(String[] argv) throws java.io.IOException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
// factory.setUsername("young");
// factory.setPassword("young");
// factory.setVirtualHost("/");
// factory.setPort(5672);
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();
}
}
package org.young.common.test;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
* Created by young on 16/10/7.
*/
public class Recv {
private final static String QUEUE_NAME = "mq.queue";
public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
// factory.setUsername("young");
// factory.setPassword("young");
// factory.setVirtualHost("/");
// factory.setPort(5672);
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");
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);
}
}
[*] Waiting for messages. To exit press CTRL+C
[x] Received 'Hello World!'
这样 上面的步骤就完成了。后来查看一下源码 发现 如果你什么都不设置。源码下面是有默认设置的。
下面要是遇到什么问题,会在这篇文章下面更新。