老师的方案已经有点过时了,这个课程的讨论去很不活跃,老师回复的也很不及时。我也遇到同样的问题,最新的解决方案如下,希望能给其他兄弟提供帮助:
package
com.rabbitmq.demo.quickstart;
import
java.io.IOException;
import
java.util.concurrent.TimeoutException;
import
com.rabbitmq.client.AMQP;
import
com.rabbitmq.client.Channel;
import
com.rabbitmq.client.Connection;
import
com.rabbitmq.client.ConnectionFactory;
import
com.rabbitmq.client.Consumer;
import
com.rabbitmq.client.DefaultConsumer;
import
com.rabbitmq.client.Envelope;
public
class
MsgConsumer {
private
final
static
String QUEUE_NAME =
"test001"
;
public
static
void
main(String[] args)
throws
IOException, TimeoutException {
ConnectionFactory connectionFactory =
new
ConnectionFactory();
connectionFactory.setHost(
"127.0.0.1"
);
connectionFactory.setUsername(
"guest"
);
connectionFactory.setPassword(
"guest"
);
connectionFactory.setPort(
5672
);
connectionFactory.setVirtualHost(
"/"
);
Connection connection =
null
;
Channel channel =
null
;
try
{
connection = connectionFactory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,
false
,
false
,
false
,
null
);
System.out.println(
"We consumer are waiting your messages"
);
Consumer consumer =
new
DefaultConsumer(channel){
@Override
public
void
handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte
[] body)
throws
IOException {
String message =
new
String(body,
"UTF-8"
);
System.out.println(
"Customer Received '"
+ message +
"'"
);
}
};
channel.basicConsume(QUEUE_NAME,
true
, consumer);
}
catch
(Exception e) {
System.out.println(
"Opps, there is something wrong!"
);
e.printStackTrace();
}
finally
{
System.out.println(
"Connection was closed!"
);
}
}
}