package com.lovecoding.rabbitmq.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {

    public static void main(String[] args) throws IOException, TimeoutException {

        //创建一个连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(25672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("123456");
        Connection connection = connectionFactory.newConnection();

        //创建一个通道
        Channel channel = connection.createChannel();

        //创建一个队列
        String queueName = "testQueue";
        channel.queueDeclare( queueName, false, false, false, null );

        //监听队列消息， 如果有消息则会回调客户端
        channel.basicConsume(queueName, new DefaultConsumer(channel){

            //处理消息函数
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException
            {
                //应答当前消息， 队列可以删除消息了
                channel.basicAck(envelope.getDeliveryTag(), false);
                //我们收到消息后打印消息
                System.out.println( new String( body ) );
            }

        });

    }

}
