rabbitmq的基本使用
java客户端下载
http://repo1.maven.org/maven2/com/rabbitmq/amqp-client/3.5.7/amqp-client-3.5.7.jar
向队列推送消息
package main;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ProduceMain {
private final static String QUEUE_NAME = "MyQueueName";
public static void main(String[] args){
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try {
//创建连接
Connection connection = factory.newConnection();
//创建通道
Channel channel = connection.createChannel();
//指定 通道 使用的队列,队列还不存在时创建队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String msg ;
for (int i=0;i<100;i++) {
msg = "msg"+String.valueOf(i);
//向队列添加消息
channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
System.out.println("Sent [" + msg + "]");
Thread.sleep(100);
}
channel.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
从队列中取出消息
package main;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
public class ConsumeMain {
private final static String QUEUE_NAME = "MyQueueName";
public static void main(String[] args) {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try {
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//指定 通道 使用的队列,队列还不存在时创建队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("Access "+QUEUE_NAME+", waiting...");
//创建队列消费者
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("Get [" + message + "]");
}
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (ShutdownSignalException e) {
e.printStackTrace();
} catch (ConsumerCancelledException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}