生产者:
public class RabbitMQProduce {
public static void main(String[] args) throws IOException, InterruptedException {
ConnectionFactory factory =new ConnectionFactory();
String Query_Name="test";
factory.setHost("localhost");
Connection conn = factory.newConnection();
Channel channel =conn.createChannel();
//声明exchange与queue
String queryName =channel.queueDeclare(Query_Name, false, false, false, null).getQueue();
//发送消息
for(int i=0;i<20;i++){
if(i%5==0){
Thread.sleep(2000);
}
byte[] messageBodyBytes =(i+"service").getBytes();
channel.basicPublish("", queryName, null, messageBodyBytes);
System.out.println("发送.."+i);
}
channel.close();
conn.close();
}
消息消费者
public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
ConnectionFactory factory =new ConnectionFactory();
String Query_Name="test";
factory.setHost("localhost");
Connection conn = factory.newConnection();
Channel channel =conn.createChannel();
//声明exchange与queue
QueueingConsumer consumer = new QueueingConsumer(channel);
boolean autoAck = false;
channel.basicConsume(Query_Name, autoAck, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
//确认消息已经收到
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
System.out.println("接受'" + message + "'");
}
}