1. 程式人生 > >RabbitMQ佇列與訊息的持久化

RabbitMQ佇列與訊息的持久化

 import com.rabbitmq.client.ConnectionFactory;
 2 import com.rabbitmq.client.Connection;
 3 import com.rabbitmq.client.Channel;
 4 import com.rabbitmq.client.QueueingConsumer;
 5 publicclass ClientReceive1 {
 6 publicstaticfinal String queue_name="my_queue";
 7 publicstaticfinalboolean autoAck=false;
 8 public
staticfinalboolean durable=true;
 9 publicstaticvoid main(String[] args)
10 throws java.io.IOException,java.lang.InterruptedException{
11         ConnectionFactory factory=new ConnectionFactory();
12         factory.setHost("localhost");
13         factory.setVirtualHost("my_mq");
14         factory.setUsername(
"zhxia");
15         factory.setPassword("123456");
16         Connection connection=factory.newConnection();
17         Channel channel=connection.createChannel();
18         channel.queueDeclare(queue_name, durable, falsefalsenull);
19         System.out.println("Wait for message");
20 channel.basicQos(
1); //訊息分發處理21         QueueingConsumer consumer=new QueueingConsumer(channel);
22         channel.basicConsume(queue_name, autoAck, consumer);
23 while(true){
24             Thread.sleep(500);
25             QueueingConsumer.Delivery deliver=consumer.nextDelivery();
26             String message=new String(deliver.getBody());
27             System.out.println("Message received:"+message);
28             channel.basicAck(deliver.getEnvelope().getDeliveryTag(), false);
29         }
30     }
31 }