public class Customer {
public static void main(String[] args) throws IOException, TimeoutException {
//创建链接mq的连接工厂对象
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置连接rabbitmq主机
connectionFactory.setHost("192.168.121.200");
//设置端口号
connectionFactory.setPort(5672);
//设置连接哪个虚拟主机
connectionFactory.setVirtualHost("/zhbj");
//设置访问虚拟主机的用户名和密码
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
//获取连接对象
Connection connection = connectionFactory.newConnection();
//获取连接中通道
final Channel channel = connection.createChannel();
//通道绑定对应消息队列
//参数1:队列名称,如果队列不存在自动创建
//参数2:用来定义队列特性是否需要持久化,true为持久化,false为不持久化
//参数3:exclusive,是否独占队列,true为独占队列,false为不独占
//参数4:autoDelete:是否在消费完成后自动删除队列,true为自动删除,false为不自动删除
//参数5:额外附加参数
channel.queueDeclare("hello",false,false,false,null);
//消费消息
//参数1:交换机名称,参数2:队列名称,参数3:传递消息额外设置,参数4:消息的具体内容
channel.basicConsume("hello",false,new DefaultConsumer(channel){
/**
* No-op implementation of {@link Consumer#handleDelivery}.
*
* @param consumerTag
* @param envelope
* @param properties
* @param body
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("new String(body)="+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
});
//channel.close();
//connection.close();
}
}